如果为null,则行不可见

时间:2014-02-05 18:13:17

标签: c# winforms datagridview

我使用Windows窗体使用datagridview构建应用程序。每个数据网格顶部都包含一个空行,我怀疑这是我填充它们的方式,但是当我走到最后时,我不愿意改变我的任何代码,因为我是初学者。

是否有一种简单的方法可以检查行是否为空,然后将其设置为不可见?

我正在使用的代码:

private void displayInGrid_Customers(string sqlcmd)
{
    customersDataGridView.Rows.Clear();

    connect.Open();

    command.Connection = connect;
    command.CommandText = sqlcmd;

    reader = command.ExecuteReader();
    customersDataGridView.Rows.Add();

    while (reader.Read())
    {
        DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();

        rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
        rowadd.Cells[1].Value = reader["Forename"].ToString();
        rowadd.Cells[2].Value = reader["Surname"].ToString();
        rowadd.Cells[3].Value = reader["Address"].ToString();
        rowadd.Cells[4].Value = reader["Town"].ToString();
        rowadd.Cells[5].Value = reader["Postcode"].ToString();
        rowadd.Cells[6].Value = reader["Date_Of_Birth"].ToString();
        rowadd.Cells[7].Value = reader["Phone_Number"].ToString();
        rowadd.Cells[8].Value = reader["Email"].ToString();
        rowadd.Cells[9].Value = reader["Current_Rental"].ToString();
        this.customersDataGridView.AllowUserToAddRows = false;
        customersDataGridView.Rows.Add(rowadd);
    }
    reader.Close();
    connect.Close();
}

private void button_view_all_customers_Click(object sender, EventArgs e)
{
    command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
                          + "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
                          + "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
    string cmd = command.CommandText;
    displayInGrid_Customers(cmd);
}

1 个答案:

答案 0 :(得分:1)

您可以使用IsNullOrWhiteSpace。但在此之前,你必须检查你的sql语句,为什么你有空行结果。

while (reader.Read())
{
    DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();

    if (!string.IsNullOrWhiteSpace(reader["Customer_ID"].ToString()))
    {
         rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
         //Others Stuff
         //...
         this.customersDataGridView.AllowUserToAddRows = false;
         customersDataGridView.Rows.Add(rowadd);
    }
}