Accessing Sql server and reading data from it in c#
i need a .net code for accessing the database in sql server and reading data from it and displaying it in datagrid view.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Sunny SharmaRank #223 · 11.1K reputationPosted Jun 4, 2013, 10:40 AM EDT
Please find below the procedure to access SQL Server database and bind it to a GridView:
----------------------------------------------------------
protected void btnFillGridView_Click(object sender, EventArgs e)
{
string ConnectionString="Server=LOCALHOST;Database=myDB;Integrated Security=True;";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select * from tablename", con);
try
{
con.Open();
}
catch (Exception ex)
{
// Database connection error
}
if (con.State == ConnectionState.Open)
{
da.Fill(dt);
}
if (con.State == ConnectionState.Open)
{
try
{
con.Close();
}
catch { }
}
//Bind the DataSource
if (dt.Rows.Count > 0) //check if dt is not empty
{
gdView.DataSource = dt;
gdView.DataBind();
}
}
---------------------------------------------------
Please don't forget to accept this as answer if it helps :)
Thanks.
ejaz ul haq10 reputationPosted Jun 4, 2013, 6:44 PM EDT
Jignesh TrivediRank #16 · 50.3K reputationPosted Jun 4, 2013, 7:06 PM EDT
hi,
Please refer following link it might help you.
http://csharp-guide.blogspot.in/2012/06/binding-data-to-datagridview-in-c.html
http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
http://www.codecandle.com/articles/csharp/ado.net/reading-data-from-sql-server-instance-database-(datareader-method).html
Sunny SharmaRank #223 · 11.1K reputationPosted Jun 4, 2013, 8:25 PM EDT
Actually the code below is relative to Grid View Web Forms.
----------------------------------------------------------
gdView.DataSource = dt;
gdView.DataBind();
----------------------------------------------------------
If you're using a Win Form then just remove the second line of code. ("gdView.DataBind();").
Happy Coding :)
Thanks.