Home
Manage Your Code
Snippet: DataReader - DataTable - GridView (C#)
Title: DataReader - DataTable - GridView Language: C#
Description: Create a Datareader, create a Datatable and insert in a Gridview. Views: 345
Author: Paulo Almeida Date Added: 11/21/2007
Copy Code  
1        protected void Button1_Click(object sender, EventArgs e)
2        {
3            string Server = "SAPHIRA";
4            string Catalog = "MyDatabase";
5            string UserID = "hz10452";
6            string Password = "password";
7
8            string ConnectionString = "Provider=SQLNCLI;Server=" + Server + ";Database=" + Catalog + ";Uid=" + UserID + ";Pwd=" + Password + ";";
9
10            string sSQL = "SELECT ID, Text, description from tblTEST";
11            OleDbDataReader dr;
12            OleDbConnection oCnn = new OleDbConnection(ConnectionString);
13            OleDbCommand oCmd = oCnn.CreateCommand();
14
15            DataTable mTable = new DataTable();
16            DataRow mLine;
17            mTable.Columns.Add(new DataColumn("ID", typeof(string)));
18            mTable.Columns.Add(new DataColumn("Text", typeof(string)));
19            mTable.Columns.Add(new DataColumn("Description", typeof(string)));
20
21            oCnn.Open();
22            oCmd.CommandText = sSQL;
23            dr = oCmd.ExecuteReader();
24            while (dr.Read())
25            {
26                mLine = mTable.NewRow();
27                mLine["ID"] = dr["ID"].ToString();
28                mLine["Text"] = dr["Text"].ToString();
29                mLine["Description"] = dr["Description"].ToString();
30                mTable.Rows.Add(mLine);
31            }
32            dr.Close();
33            oCnn.Close();
34            
35            this.GridView1.DataSource = mTable;
36            this.GridView1.DataBind();
37        }