Aamir Rizwan Aamir Rizwan - 2 months ago 16
ASP.NET (C#) Question

How to display data in gridview from MS Access?

I want to display information of user stored in a MS Access database. The user enters his userid and on clicking a button following function is called. But no data is being displayed. What am I doing wrong ?

System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbDataAdapter da;

protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
con.Close();
}

Answer

You need to call GridView1.DataBind()

 GridView1.DataSource = t;
 GridView1.DataBind();

Just a side-note, it is good practice to wrap your connection with using

using(con = new System.Data.OleDb.OleDbConnection())
{
   con = new System.Data.OleDb.OleDbConnection();
   con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" 
   + "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
   con.Open();
   ...
   ...
}

This ensures your connection is properly disposed after use