How to create rows and columns and realize DataReader reading by DataTable
Editor to share with you how DataTable creates rows and columns and realizes DataReader reading. I hope you will get something after reading this article. Let's discuss it together.
Public DataTable read ()
{
String str = "select id,UserName,UserPwd from Users"; / / SQL statement
SqlCommand cmd = new SqlCommand (str, conn)
DataTable table = new DataTable (); / / create the table
DataColumn dc=null;// definition
Dc=table.Columns.Add ("number", Type.GetType ("System.Int32")); / / create columns, column names and types
Dc.AutoIncrement = true; / / Auto column
Dc.AutoIncrementSeed = 1; / / starting from 1
Dc.AutoIncrementStep = 1 / step size is 1
Dc=table.Columns.Add ("user name", Type.GetType ("System.String")); / / create the second column
Dc=table.Columns.Add ("password", Type.GetType ("System.String")); / / create the third column
DataRow newRow
Conn.Open ()
SqlDataReader reader = cmd.ExecuteReader ()
While (reader.Read ())
{
NewRow = table.NewRow (); / / create a new line
NewRow ["number"] = reader ["id"]; / / assign a value to a row
NewRow ["user name"] = reader ["username"] .ToString ()
NewRow ["password"] = reader ["userpwd"] .ToString ()
Table.Rows.Add (newRow); / / add rows to the table
}
Return table
}
After reading this article, I believe you have some understanding of "how to create rows and columns and achieve DataReader reading in DataTable". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!