How Will You Fill The Gridview by Using Datatable Object at Runtime?
How Will You Fill The Gridview by Using Datatable Object at Runtime?
runtime?
using System;
using System.Data;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("Employee"); // Create the table object
DataColumn dc = new DataColumn();
DataRow dr;
dc.ColumnName = "ID"; //Heading of the coloumn
dc.DataType = Type.GetType("System.Int32"); //Set the type of ID as Integer
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "ItemName";
dc.DataType = Type.GetType("System.String"); //Set the type of ItemName as String
dt.Columns.Add(dc);
for (int i = 0; i <= 4; i++) //This code will create 5 new rows
{
dr = dt.NewRow();
dr["id"] = i;
dr["ItemName"] = "Item " + i;
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
This method works on select SQL query. It returns the DataReader object. Use DataReader
read () method to retrieve the rows.
ExecuteScalar :
This method returns single value. Its return type is Object
ExecuteNonQuery :
If you are using Insert, Update or Delete SQL statement then use this method. Its return
type is Integer (The number of affected records).
using System;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=Your data source name;Initial
Catalog=Demo;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from employee";
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DropDownList1.Items.Add(reader[1].ToString());
}
}
else
{
Label1.Text="No rows found.";
}
reader.Close();
con.Close();
}
}
In the above given example a DropdownList has been taken that is filled by second column
of employee table.