This Post explains "how to populate gridview with MsSql Data".By assuming you already know about creating web application project in asp.Net.We straightly move to coding.
For this tutorial I am using Northwind Database.You can download NorthWind database from
here.In this tutorial i am going to bind "Customers" table to the gridview.
Following is the Html markup consist asp:Gridview control.
AutoGeneratedColumns = false(Avoids the creating for empty rows).
DataField value maps the sql colums to the Girdview.
<asp:GridView ID="grdView" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="Customer Name" />
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
</Columns>
</asp:GridView>
Code Behind
public partial class Default : System.Web.UI.Page
{
SqlCommand cmd;
DataTable dt;
SqlDataAdapter sda;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
cmd = new SqlCommand();
dt = new DataTable();
BindData();
}
}
private void BindData()
{
string Constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(Constr);
cmd.Connection = sqlcon;
cmd.CommandText = "SELECT top 10 CustomerID,CompanyName,ContactName from Customers";
cmd.CommandType = CommandType.Text;
sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
grdView.DataSource = dt;
grdView.DataBind();
}
}
Connection String:
Add the following Connection string to your webconfig file.
<connectionStrings>
<add name="constr" connectionString="Data Source=DESKTOP-KSHIC44\GAMER;Initial Catalog=NORTHWND;Integrated Security=SSPI;"/>
</connectionStrings>
Output:
No comments :
Post a Comment