Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bind a GridView from database

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

like image 442
Mrityunjay Malliya Avatar asked Sep 23 '13 13:09

Mrityunjay Malliya


People also ask

What is GridView DataBind () in asp net?

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.

Which are the steps to set up database connectivity in GridView?

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.


2 Answers

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>;
like image 118
Soner Sevinc Avatar answered Sep 24 '22 13:09

Soner Sevinc


<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();
        }
like image 39
Meena Avatar answered Sep 25 '22 13:09

Meena