Page_load Bind gridview control in asp.net


Description:-

This is a simple task, we made a common function bindgrid () which binds our Gridview control with data.

On page load will call this function, and now whenever the page gets load, function bindgrid () gets call and data gets display. Our final code looks as shown below.

Create Table:-
CREATE TABLE [dbo].[Food](
 [Fid] [bigint] IDENTITY(1,1) NOT NULL,
 [Fname] [nvarchar](100) NULL,
 [Fprice] [bigint] NULL,
 [Recstatus] [char](1) NULL,
PRIMARY KEY CLUSTERED 
(
 [Fid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Default.aspx:-
<asp:GridView ID="GridView2" runat="server"></asp:GridView>

Web.Config:-
<connectionStrings>
    <add connectionString="ConnectionString" name="DBCS" providerName="System.Data.SqlClient"/>   
</connectionStrings>

Default.aspx.cs:-
string Str = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    bindgrid();
  }
}

public void bindgrid()
{
  SqlConnection con = new SqlConnection(Str);
  SqlCommand cmd = new SqlCommand("select * from food ", con);
  cmd.CommandType = CommandType.Text;
  SqlDataAdapter da = new SqlDataAdapter();
  da.SelectCommand = cmd;
  DataTable dt = new DataTable();
  da.Fill(dt);
  if (dt.Rows.Count > 0)
  {
    GridView1.DataSource = dt;
    GridView1.DataBind();
  }
  else
  {
    DataRow dr = dt.NewRow();
    dt.Rows.Add(dr);
    GridView1.DataSource = dt;
    GridView1.DataBind();
  }
}

Related Posts

Previous
Next Post »

Thanks for comments.....