简体   繁体   中英

C# winform Filter combobox items based on datagridview values

I have a combobox called cmbCaseRemain its data populated from datatable by code

cmbCaseRemain.DataSource = ce.GET_ALL_CASEREMAIN();
cmbCaseRemain.DisplayMember = "caseRemain";
cmbCaseRemain.ValueMember = "idCaseRemain";

and I have a datagridview called dgv_CaseRemain gets its data from another datatable

DataTable dt = new DataTable();
dt = ce.GET_ALL_CASEREMAIN_FILTER(Convert.ToInt32(txtidCase.Text));
dgv_CaseRemain.DataSource = dt;

I'm using the combobox to add items to the datagrid view ... and i want after every adding to filter the items in the combobox so the user can't add the same value twice ... so I created a stored procedure with a parameter

CREATE PROC [dbo].[FILTER_CMB_CASEREMAIN]
    @ID int
AS
    SELECT 
        [idCaseRemain], [caseRemain]
    FROM 
        [dbo].[tblCaseRemain]
    LEFT OUTER JOIN 
        tblCase_Link_Remain ON idCaseRemain = idCaseRemain_L
    WHERE 
        [idCaseRemain] <> @ID;

and using a code to pass the parameter which filter the combobox when i click on it

DataTable dt = new DataTable();
dt = ce.FILTER_CMB_CASEREMAIN(Convert.ToInt32(this.dgv_CaseRemain.CurrentRow.Cells[1].Value));

if (dt.Rows.Count > 0)
{
    cmbCaseRemain.DisplayMember = "caseRemain";
    cmbCaseRemain.ValueMember = "idCaseRemain";
    cmbCaseRemain.DataSource = dt;
}

but I got an error

Object reference not set to an instance of an object.

Thank you

( sorry for my bad english :-) )

ok. Got it. As I said, it was error on that line. Use below code. Below I add the validation to check the null value.

int n = 0;
DataTable dt;
if (this.dgv_CaseRemain.CurrentRow.Cells[1].Value != null)
{
    if (int.TryParse(this.dgv_CaseRemain.CurrentRow.Cells[1].Value.ToString(), out n))
    {
        dt = ce.FILTER_CMB_CASEREMAIN(n);
    }
}
if (dt!=null && dt.Rows.Count > 0)
{

    cmbCaseRemain.DisplayMember = "caseRemain";
    cmbCaseRemain.ValueMember = "idCaseRemain";
    cmbCaseRemain.DataSource = dt;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM