Reputation: 2004
I am trying to display a database table in a DataGrid but the DataGrid isn't displaying. All I have is a textbox and under it I want the DataGrid to display the table. The textbox is displaying but the DataGrid isn't.
<table>
<tbody>
<tr>
<td class="Header">Public Holiday Date</td>
<td>
<asp:TextBox runat="server" ID="txtDate" rel="datepicker" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:DataGrid runat="server" id="dataGridView1" AutoGenerateColumns="true"></asp:DataGrid>
</td>
</tr>
</tbody>
</table>
The code for getting the data from the database:
private DataSet GetBankHolidays()
{
DataSet ds = new DataSet();
string sql = "proc_GetAllCustomers";
string query = "SELECT BankHol FROM bankholidays";
DataTable dt = new DataTable();
using (MySql.Data.MySqlClient.MySqlDataAdapter adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(sql, DataUtils.ConnectionStrings["TAT"]))
{
adapter.SelectCommand.CommandType = CommandType.Text;
adapter.SelectCommand.CommandText = query;
adapter.Fill(dt);
ds.Tables.Add(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
}
return ds;
}
And I'm calling this method in the page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetBankHolidays();
}
}
Upvotes: 0
Views: 977
Reputation: 146
Your code lacks {dataGridView1.DataBind();}
command.
Use the DataBind()
method to bind data from a data source to the GridView
control.
Upvotes: 1
Reputation: 13474
In your coding you are using stored procedure
but you have
mentioned command type as text
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
You need to bind DataSource to the DataGrid
dataGridView1.DataBind();
Final code
using (MySql.Data.MySqlClient.MySqlDataAdapter adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(sql, DataUtils.ConnectionStrings["TAT"]))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.CommandText = query;
adapter.Fill(dt);
ds.Tables.Add(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
}
Upvotes: 0
Reputation: 21795
You need to call the DataBind method:-
dataGridView1.DataBind();
Apart from this I would suggest you to separate out the DAL & UI code.
Upvotes: 1