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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sunny SharmaPosted Jun 5, 2013, 12:25 AM
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.
Jignesh TrivediPosted Jun 4, 2013, 11:06 PM
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
ejaz ul haqPosted Jun 4, 2013, 10:44 PM
Sunny SharmaPosted Jun 4, 2013, 2:40 PM
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.