The following are the basic steps to get data from SQL database and bind to GridView control in ASP.net.
I have a Database named ABC with a table named Products, I want to get all the rows in Products table.
Step 1: Create new Project
Launch Visual Studio 2010, click on File->New->Website to create a new ASP.NET website Project.
Step 2: Create a new Page
Right click on the Project on the Solution Explorer Panel. Select Add->New Item. Then, choose Web Form. I'd like to name it Products.aspx
Step3: Add the following code to the Products.aspx file
<form id="form1" runat="server">
<div>
<asp:GridView ID="grid" runat="server">
</asp:GridView>
</div>
</form>
<div>
<asp:GridView ID="grid" runat="server">
</asp:GridView>
</div>
</form>
Step 4: Add the following code to the Products.aspx.cs file
protected void bindToGrid()
{
string connstr = "Data Source=WIN2K8; Initial Catalog=ABC;User ID=sa; Password=123";
DataSet ds = new DataSet();
SqlDataAdapter da;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
da = null;
string strsql = "Select * from Products";
da = new SqlDataAdapter(strsql, conn);
da.Fill(ds, "ProductsTable");
grid.DataSource = ds.Tables["ProductsTable"].DefaultView;
grid.DataBind();
}
on the Page_Load event, call the above method
Step 5: Under the configuration tab of the web.config file, add the following code:
<appSettings>
<add key="ConnectionString" value="Data Source=WIN2K8;Initial Catalog=Products;User ID=sa; Password=123 "/>
</appSettings>
<connectionStrings>
<add name="ProductsConnectionString" connectionString="Data Source=WIN2K8;Initial Catalog=Products;User ID=sa; Password=Thien123" providerName="System.Data.SqlClient"/>
</connectionStrings>
Step 6: Build the project
Right click on the project on the Solution Explore and choose Build.
Right click on the Products.aspx file and select View in browser:
We get the result as the bellow figure:
Hope this helps!
0 comments:
Post a Comment