Introduction:-
Hello all today i will explain you "How to fill gridview from datatable in asp.net"
Please follow the below steps:-
1)Create a connection string in Web.config File.
<connectionStrings>
<add name="sqlConnecrtion" connectionString="Data Source=MICROSOFTDOTNET;Initial Catalog=SEPTNew;Trusted_connection=True" />
</connectionStrings>
2) Drag the GridView on to the .aspx page.
3) write the below code in your .aspx.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
string _con = ConfigurationManager.ConnectionStrings["sqlConnecrtion"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getdata();
}
}
private void getdata()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(_con))
{
con.open();
string str = "Select * from City_Master ";
using (SqlCommand cmd = new SqlCommand(str,con))
{
using(SqlDataAdapter sd=new SqlDataAdapter(cmd))
{
sd.Fill(dt);
}
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Execute your program using F5 or start project.
--------------------------Thank you -------------------------
No comments:
Post a Comment