Vik
Vik

Reputation: 89

Change datagridview cell to combobox if empty/(null) c#

I am working on a windows form using C# and sql server 2014. As title says I want to change DataGridView cell/s in a specific column to combobox field if they are empty.

My form load method is like this:

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

        dataGridViewAP.DataSource = DBConn.getAdminInfo();

    }

I have a method getAdminInfo() like this

    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;
        }
    }

I want to add combobox cell to Account status Column cell to update it with the selected value if it is empty.

Hope my question is clear, any ideas?

Upvotes: 0

Views: 615

Answers (1)

Graffito
Graffito

Reputation: 1718

Prior to bind the DataTable to DataGridView, create the DataGridViewComboBoxColum corresponding to your specific column and set its DataPropertyName property of the column. Specify the ComboBox items through binding.

Code to insert in your load function:

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();

Upvotes: 2

Related Questions