user123456789
user123456789

Reputation: 2004

Gridview not displaying values from Database

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

Answers (4)

Derpuku Der
Derpuku Der

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

Nagaraj S
Nagaraj S

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

Imad
Imad

Reputation: 7490

write dataGridView1.DataBind(); below dataGridView1.DataSource = dt;

Upvotes: 1

Rahul Singh
Rahul Singh

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

Related Questions