如果为空/(null)c#,将datagridview单元格更改为组合框

时间:2015-07-11 20:36:37

标签: c# winforms datagridview combobox

我正在使用C#和sql server 2014处理Windows窗体。如标题所示,我想将特定列中的DataGridView单元格更改为组合框字段(如果它们为空)。

我的表单加载方法是这样的:

private void AdminPanel_Load(object sender, EventArgs e)
    {
        DBConn.ConnectToDatabase();

        dataGridViewAP.DataSource = DBConn.getAdminInfo();

    }

我有一个像这样的方法getAdminInfo()

    public DataTable getAdminInfo()
    {
        try
        {
            string strCommand = "SELECT Customer.AccountNo AS [Account Number], Customer.Name AS [Customer Name], Customer.Adrs1 AS [Address 1], Customer.Adrs2 AS [Address 2], Customer.City AS [City], Customer.Province AS [Province], Customer.PostalCode AS [Postal Code], Customer.Email1 AS [Email], Manifest.Class AS [Class], Manifest.Rname AS [Recipient Name], Manifest.Adrs1 AS [Dest. Address 1],  Manifest.Adrs2 AS [Dest. Address 2],  Manifest.City AS [City],  Manifest.State AS [State], Manifest.PostalCode AS [Postal Code], Manifest.Country AS [Country], Manifest.Item AS [Description], Manifest.Weight AS [Weight (lb)], Manifest.Value AS [Value (USD)], Manifest.DateTime AS [Date/Time], Manifest.CheckedBy AS [Checked By], Customer.AccStatus AS [Account Status] FROM Customer INNER JOIN Manifest ON Customer.AccountNo = Manifest.FKAccountNo WHERE CONVERT(DATE,DateTime)=CONVERT(Date,GETDATE())";
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(strCommand, conn);
            da.Fill(dt);
            return dt;
        }
        catch (SqlException e)
        {
            MessageBox.Show(e.Source + "/n" + e.Message + "/n" + e.StackTrace);
            return null;
        }
    }

我想将组合框单元添加到帐户状态列单元格,如果它为空,则使用所选值更新它。

希望我的问题清楚,有什么想法吗?

1 个答案:

答案 0 :(得分:2)

在将DataTable绑定到DataGridView之前,创建与特定列对应的DataGridViewComboBoxColum并设置其列的DataPropertyName属性。通过绑定指定ComboBox项。

要在加载函数中插入的代码:

DataGridViewComboBoxColumn cbcol = new DataGridViewComboBoxColumn ();
cbcol.Name             = "Account_Status" ;
cbcol.DataPropertyName = "Account Status" ; // DataTable column name
cbcol.DataSource       =  ...             ; // ComboBox DataSource
dataGridViewAP.Columns.Add(cbcol);
dataGridViewAP.DataSource = DBConn.getAdminInfo();