Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
how to display data from sqlsrver in gridview using asp.net and C#
Posted

Hi,
This is a sample which SqlDataSource is used to fill the GridView:

XML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="ProductID" DataSourceID="ProductsDataSource"
    EnableViewState="False">
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="ProductID"
            InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
        <asp:BoundField DataField="ProductName" HeaderText="Product Name"
            SortExpression="ProductName" />
        <asp:BoundField DataField="UnitPrice" HeaderText="Price"
            SortExpression="UnitPrice" DataFormatString="{0:c}"
            HtmlEncode="False" />
    </Columns>
</asp:GridView>

<asp:SqlDataSource ID="ProductsDataSource" runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionStringNameInConfigFile %>"
    SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]">
</asp:SqlDataSource>


I hope it will help,
Cheers
 
Share this answer
 
 
Share this answer
 
C#
public void Bind()
  {

      setConnectionString();

      query = "select * from userinfo";
      //Session["GridView1"] = EmpBal.bindgridBAL(query, conString);
      DataSet ds = EmpBal.bindgridBAL(query, conString);
      GridView1.DataSource = ds;
      GridView1.DataBind();

  }

C#
protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           //if (Session["username"] == null)
           //{
           //    Response.Redirect("Login.aspx");
           //}

           //else
           //{
               Bind();
           //}

       }

   }
 
Share this answer
 
There are many ways and lot of articles available, if you searched in Google you will definitely get tons of articles on this requirement anyways the simplest way

C#
private void BindGrid()
{
SqlConnection con =new SqlConnection("yourconnectionstring");
SqlCommand cmd=new SqlCommand("Select * from yourtablename",con);
con.open();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds=new DataSet();
da.SelectCommand=cmd;
da.Fill(ds);
Gridview1.DataSource=ds;
GridView1.Databind();
}


In your page load call as follows

C#
If(!IsPostBack)
{
BindGrid()
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900