How to bind a GridView?
I want to display my table data in a gridview.
I have createed SQL table EmpDetail with columns ID, Name, Salary Data
It binds the DataSource specified with the GridView to the Grid. For example if you have. DataTable SomeDataTable = //filled with a result from a SQL Query gridView1.
Step 1 – Open the Visual Studio –> Create a new empty Web application. Step 2 – Create a New web page. Step 3 – Drag and drop GridView Control on web page from toolbox. Step 5 – Make connection between Database and web application.
Try below code according to your scenario
I hope it helps you
protected void GridviewBind ()
{
    using (SqlConnection con = new SqlConnection("Data Source=RapidProgramming;Integrated Security=true;Initial Catalog=RPDB"))
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
        SqlDataReader dr = cmd.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();
        con.Close();
    }
}
<asp:GridView ID="GridView1" runat="server" BackColor="White" 
              BorderColor="#3366CC" BorderStyle="None" 
              BorderWidth="1px" CellPadding="4"
              style="text-align: center; margin-left: 409px" Width="350px">
  <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
  <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
  <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
  <RowStyle BackColor="White" ForeColor="#003399" />
  <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
  <SortedAscendingCellStyle BackColor="#EDF6F6" />
  <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
  <SortedDescendingCellStyle BackColor="#D6DFDF" />
  <SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>;
                        <asp:GridView ID="GridView1" runat="server">
</asp:GridView>
protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        bindData();   
    }
}
public void bindData() {
        SqlConnection con=new SqlCponnection(ConnectionStrings);
        SqlDataAdapter da = new SqlDataAdapter("select * from  Your TableName", con);
        DataSet ds = new DataSet();
        try {
            da.Fill(ds, "YourTableName");
            GridView1.DataSource = ds;
            GridView1.DataBind();
        } catch (Exception e) {
           Response.Write( e.Message);
        } finally {
            ds.Dispose();
            da.Dispose();
            con.Dispose();
        }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With