C#Datagridview - 每行不同值的组合框

时间:2017-05-12 08:21:39

标签: c# datagridview

我已经完成了我常用的谷歌搜索,但我遇到的所有主题似乎都没有像我正在做的那样做,或者想以同样的方式做到这一点。我能找到的最接近的是

https://www.experts-exchange.com/questions/23555139/How-to-filter-values-in-DataGridViewComboBoxColumn.html

忽略这是VB并且我在C#中工作,他们将数据集/源等设置在顶部并逐行创建新列,而我通过网格创建数据SQL查询。简而言之,我希望这样做:

  • 有一个datagridview,通过SQL查询填充信息,组合框具有基于每行另一个值的不同值。

我已经完成了所有工作并进行了设置,我遇到的问题是将其作为单个组合框,在逐行检查结束值时使用不同的值(下面的屏幕截图使其更易于理解)

http://i67.tinypic.com/1zdqafd.jpg

“exp grade”应该是基于ID列读取的值的不同值。我尝试了一些不同的方法让它成为一个不同等级的列,但我得到第一组或第二组(如果我离开if列不存在)或我得到多列(如果我删除它为id = 2起)。第一部分是使用查询检查每行ID列的值

foreach (DataGridViewRow rw in this.dgvDDL.Rows)
                    {
                        if (Convert.ToString(rw.Cells["ID"].Value) == "1")
                        {
                            if (!dgvDDL.Columns.Contains("Exp_Grade"))
                            {

                                try
                                {
                                    DataGridViewComboBoxColumn cmbGrade = new DataGridViewComboBoxColumn();
                                    SqlConnection conn = new SqlConnection(@"");

                                    SqlCommand cmd = new SqlCommand("SELECT AREA_CODE, GRADE [Grade] "
                                                                  + "FROM RICH_DDL_TEST "
                                                                  + "WHERE IDENTIFIER = '1' "
                                                                  + "UNION "
                                                                  + "SELECT AREA_CODE, GRADE2[Grade] "
                                                                  + "FROM RICH_DDL_TEST "
                                                                  + "WHERE IDENTIFIER = '1' "
                                                                  + "UNION "
                                                                  + "SELECT AREA_CODE, GRADE3[Grade] "
                                                                  + "FROM RICH_DDL_TEST "
                                                                  + "WHERE IDENTIFIER = '1' "
                                                                  + "ORDER BY 2", conn);

                                    cmd.CommandType = CommandType.Text;
                                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                                    DataSet ds = new DataSet();
                                    da.Fill(ds);
                                    cmbGrade.DataSource = ds.Tables[0];
                                    this.dgvDDL.Columns.Insert(2, cmbGrade);
                                    this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                                    this.dgvDDL.Columns[2].Name = "Exp_Grade";
                                    cmbGrade.ValueMember = "Grade";
                                    cmbGrade.DisplayMember = "Grade";
                                }

                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OKCancel,
                                    MessageBoxIcon.Warning);
                                }
                            }
                        }

                        if (Convert.ToString(rw.Cells["ID"].Value) == "2")
                        {
                            if (!dgvDDL.Columns.Contains("Exp_Grade"))
                            {

                                try
                                {
                                    DataGridViewComboBoxColumn cmbGrade = new DataGridViewComboBoxColumn();
                                    SqlConnection conn = new SqlConnection(@"");

                                    SqlCommand cmd = new SqlCommand("SELECT AREA_CODE, GRADE [Grade] "
                                                                  + "FROM RICH_DDL_TEST "
                                                                  + "WHERE IDENTIFIER = '2' "
                                                                  + "UNION "
                                                                  + "SELECT AREA_CODE, GRADE2[Grade] "
                                                                  + "FROM RICH_DDL_TEST "
                                                                  + "WHERE IDENTIFIER = '2' "
                                                                  + "UNION "
                                                                  + "SELECT AREA_CODE, GRADE3[Grade] "
                                                                  + "FROM RICH_DDL_TEST "
                                                                  + "WHERE IDENTIFIER = '2' "
                                                                  + "ORDER BY 2", conn);

                                    cmd.CommandType = CommandType.Text;
                                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                                    DataSet ds = new DataSet();
                                    da.Fill(ds);
                                    cmbGrade.DataSource = ds.Tables[0];
                                    this.dgvDDL.Columns.Insert(2, cmbGrade);
                                    this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                                    this.dgvDDL.Columns[2].Name = "Exp_Grade";
                                    cmbGrade.ValueMember = "Grade";
                                    cmbGrade.DisplayMember = "Grade";
                                }

                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OKCancel,
                                    MessageBoxIcon.Warning);
                                }
                            }
                        }

第二组也检查,但硬编码值:

/*foreach (DataGridViewRow rw in this.dgvDDL.Rows)
                        {
                            if (Convert.ToString(rw.Cells["ID"].Value) == "1")
                            {
                                if (!dgvDDL.Columns.Contains("Exp_Grade"))
                                {
                                    try
                                    {
                                        DataGridViewComboBoxColumn a = new DataGridViewComboBoxColumn();
                                        this.dgvDDL.Columns.Insert(2, a);
                                        this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                                        this.dgvDDL.Columns[2].Name = "Exp_Grade";
                                        string[] aList = new[] { "A", "B", "C" };
                                        foreach (string str in aList)
                                        {
                                            a.Items.Add(str);
                                        }
                                    }

                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "Error at 1", MessageBoxButtons.OKCancel,
                                        MessageBoxIcon.Warning);
                                    }
                                }
                            }

                            if (Convert.ToString(rw.Cells["ID"].Value) == "2")
                            {
                                if (!dgvDDL.Columns.Contains("Exp_Grade"))
                                {
                                    try
                                    {
                                        DataGridViewComboBoxColumn b = new DataGridViewComboBoxColumn();
                                        this.dgvDDL.Columns.Insert(2, B)/>/>/>;
                                        this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                                        this.dgvDDL.Columns[2].Name = "Exp_Grade";
                                        string[] bList = new[] { "D", "E", "F" };
                                        foreach (string str in bList)
                                        {
                                            b.Items.Add(str);
                                        }
                                    }

                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "Error at 2", MessageBoxButtons.OKCancel,
                                        MessageBoxIcon.Warning);
                                    }
                                }
                            }

                            if (Convert.ToString(rw.Cells["ID"].Value) == "3")
                            {

                            }

                            if (Convert.ToString(rw.Cells["ID"].Value) == "4")
                            {

                            }*/

有人能指出我正确的方向,还是指出我做错了什么?

由于

-edit完整代码如下更新:

private void DDLTest_Load(object sender,EventArgs e)         {             Cursor.Current = Cursors.WaitCursor;

        this.dgvDDL.Focus();

        try
        {
            SqlConnection cnSQL;
            DataSet dsData;
            String strQuery = "SELECT uio.course_occurrence_code [CourseCode], uio.long_description [CourseDesc], '' [Grade], uio.owning_organisation [Area], ddl.IDENTIFIER [ID] "
                            + "FROM unit_instance_occurrences [uio] LEFT JOIN RICH_DDL_TEST [ddl] ON uio.UIO_ID = ddl.UIO_ID "
                            + "WHERE uio.calocc_occurrence_code lIKE '16%' AND uio.owning_organisation IS NOT NULL "
                            + "ORDER BY 3, 1";

            //If using database class
            cnSQL = database.AcquireConnection();

            //If using database class
            dsData = database.GetData(cnSQL, strQuery);

            cnSQL.Close();
            cnSQL.Dispose();

            if (dsData.Tables.Count > 0)
            {
                dgvDDL.DataSource = dsData.Tables[0];

                this.dgvDDL.Columns["Grade"].Visible = false;

                this.dgvDDL.AutoGenerateColumns = false;

                /*try
                {
                    DataGridViewComboBoxColumn cmbGrade = new DataGridViewComboBoxColumn();
                    SqlConnection conn = new SqlConnection(@"Data Source = EBS - DB - REPORTSE; Initial Catalog = ebslive; Persist Security Info = True; User ID = sa; Password = W0rk1ngMen5");

                    SqlCommand cmd = new SqlCommand("SELECT AREA_CODE, 'A'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'B'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'C'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'D'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'E'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'F'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'G'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'H'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'I'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'J'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "UNION "
                                                  + "SELECT AREA_CODE, 'K'[Grade] "
                                                  + "FROM RICH_DDL_TEST "
                                                  + "ORDER BY 2", conn);

                    cmd.CommandType = CommandType.Text;
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    cmbGrade.DataSource = ds.Tables[0];
                    this.dgvDDL.Columns.Insert(2, cmbGrade);
                    this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                    this.dgvDDL.Columns[2].Name = "Exp_Grade";
                    cmbGrade.ValueMember = "Grade";
                    cmbGrade.DisplayMember = "Grade";
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Warning);
                }*/
            }

            Int32 intRows = dsData.Tables[0].Rows.Count;

            try
            {
                foreach (DataGridViewRow row in dgvDDL.Rows)
                {
                    if (row.Index < intRows)
                    {
                        // row.Cells["Exp_Grade"].Value = dsData.Tables[0].Rows[row.Index]["Grade"].ToString();
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error detected",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Warning);
            }

            dsData.Tables[0].Rows.Count.ToString();
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error detected",
            MessageBoxButtons.OKCancel,
            MessageBoxIcon.Warning);
        }
    }

    private void dgvDDL_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void dgvDDL_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
       /* foreach (DataGridViewRow rw in this.dgvDDL.Rows)
        {
            bool flaga = false;
            if (Convert.ToString(rw.Cells["ID"].Value) == "1")
                flaga = true;

            if (flaga)
            {
                this.dgvDDL.Columns["Grade"].Visible = false;

                if (!dgvDDL.Columns.Contains("Exp_Grade"))
                {
                    try
                    {
                        DataGridViewComboBoxColumn a = new DataGridViewComboBoxColumn();
                        this.dgvDDL.Columns.Insert(2, a);
                        this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                        this.dgvDDL.Columns[2].Name = "Exp_Grade";
                        string[] aList = new[] { "C", "D", "E" };
                        foreach (string str in aList)
                        {
                            a.Items.Add(str);
                        }
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error at 1", MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Warning);
                    }
                }
            }

            else if (Convert.ToString(rw.Cells["ID"].Value) == "2")

            {
                this.dgvDDL.Columns["Grade"].Visible = false;

                if (!dgvDDL.Columns.Contains("Exp_Grade"))
                {
                    try
                    {
                        DataGridViewComboBoxColumn a = new DataGridViewComboBoxColumn();
                        this.dgvDDL.Columns.Insert(2, a);
                        this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                        this.dgvDDL.Columns[2].Name = "Exp_Grade";
                        string[] aList = new[] { "D", "E", "F" };
                        foreach (string str in aList)
                        {
                            a.Items.Add(str);
                        }
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error at 2", MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Warning);
                    }
                }
            }

            else if (Convert.ToString(rw.Cells["ID"].Value) == "3")
            {
                this.dgvDDL.Columns["Grade"].Visible = false;

                if (!dgvDDL.Columns.Contains("Exp_Grade"))
                {
                    try
                    {
                        DataGridViewComboBoxColumn a = new DataGridViewComboBoxColumn();
                        this.dgvDDL.Columns.Insert(2, a);
                        this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                        this.dgvDDL.Columns[2].Name = "Exp_Grade";
                        string[] aList = new[] { "G", "H", "I" };
                        foreach (string str in aList)
                        {
                            a.Items.Add(str);
                        }
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error at 3", MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Warning);
                    }
                }
            }

            else if (Convert.ToString(rw.Cells["ID"].Value) == "4")
            {
                this.dgvDDL.Columns["Grade"].Visible = false;

                if (!dgvDDL.Columns.Contains("Exp_Grade"))
                {
                    try
                    {
                        DataGridViewComboBoxColumn a = new DataGridViewComboBoxColumn();
                        this.dgvDDL.Columns.Insert(2, a);
                        this.dgvDDL.Columns[2].HeaderText = "Exp_Grade";
                        this.dgvDDL.Columns[2].Name = "Exp_Grade";
                        string[] aList = new[] { "J", "K", "L" };
                        foreach (string str in aList)
                        {
                            a.Items.Add(str);
                        }
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error at 4", MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Warning);
                    }
                }
            }
        }*/
    }

    private void dgvDDL_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void dgvDDL_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            if (e.ColumnIndex == 4)
            {
                if (dgvDDL.Rows[e.RowIndex].Cells[4].Value != null)
                {
                    DataGridViewComboBoxCell comboCell = dgvDDL.Rows[e.RowIndex].Cells[0] as DataGridViewComboBoxCell;

                    if (dgvDDL.Rows[e.RowIndex].Cells[4].Value.ToString() == "1")
                    {
                        SetCombo(1, comboCell);
                    }

                    if (dgvDDL.Rows[e.RowIndex].Cells[4].Value.ToString() == "2")
                    {
                        SetCombo(2, comboCell);
                    }

                    if (dgvDDL.Rows[e.RowIndex].Cells[4].Value.ToString() == "3")
                    {
                        SetCombo(3, comboCell);
                    }

                    if (dgvDDL.Rows[e.RowIndex].Cells[4].Value.ToString() == "4")
                    {
                        SetCombo(4, comboCell);
                    }
                }
            }
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OKCancel,
            MessageBoxIcon.Warning);
        }
    }

    private void SetCombo (int comboType, DataGridViewComboBoxCell comboCell)
    {
        comboCell.Value = "";
        comboCell.Items.Clear();

        if (comboType == 1)
        {
            comboCell.Items.Add("A");
            comboCell.Items.Add("B");
            comboCell.Items.Add("C");
            return;
        }

        if (comboType == 2)
        {
            comboCell.Items.Add("D");
            comboCell.Items.Add("E");
            comboCell.Items.Add("F");
            return;
        }

        if (comboType == 3)
        {
            comboCell.Items.Add("G");
            comboCell.Items.Add("H");
            comboCell.Items.Add("I");
            return;
        }

        if (comboType == 4)
        {
            comboCell.Items.Add("J");
            comboCell.Items.Add("K");
            comboCell.Items.Add("L");
            return;
        }

        comboCell.Items.Add("A");
        comboCell.Items.Add("B");
        comboCell.Items.Add("C");
        comboCell.Items.Add("D");
        comboCell.Items.Add("E");
        comboCell.Items.Add("F");
        comboCell.Items.Add("G");
        comboCell.Items.Add("H");
        comboCell.Items.Add("I");
        comboCell.Items.Add("J");
        comboCell.Items.Add("K");
        comboCell.Items.Add("L");
    }

1 个答案:

答案 0 :(得分:1)

我认为通过DaragridView循环来设置组合框不一定是最好的方法。使用此方法,用户必须按下按钮或其他一些机制才能触发此组合框更新。使用您链接的图片,您似乎希望根据“ID”列中的值,在组合框中显示不同的值。

示例,如果第0行“ID”列具有“1”,则将该行的组合框值设置为“A,B和C”。如果“ID”列中的值为2,则将该行上的组合框值设置为“D,E和F”。如果“ID”列中的值不是1或2,则不清楚要将组合框值设置为什么。我假设“A,B,C,D,E,F”

我确信有几种方法可以实现这一点,并且由于规范并不完全清楚,实现此目的的一种可能方法是在“ID”列单元格中的值更改时手动设置每个组合框。换句话说,如果“ID”列中的单元格值发生更改,我们可能需要更改该行的组合框值。这可以使用DataGridView s CellChangedEvent来实现。触发此事件时,可以检查更改的值是否在“ID”列中,如果是,则根据“ID”列中的值更新行组合框。

如果用户更改“ID”列中的值以及将数据读入网格,也会使用CellValueChanged事件更新组合框。希望这是有道理的。

下面的代码演示了这一点。 DataGridView设置为两列,第一列是组合框列,第二列是“ID”。设置列后,会添加几行。请注意,在“ID”列中的值更改之前,不会设置组合框值。如果更改“ID”列中的值,则该行上的组合框应更改为适当的值。希望这会有所帮助。

private void Form1_Load(object sender, EventArgs e) {
  SetColumns();
  AddRows();
}

private void SetColumns() {
  DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
  comboColumn.Name = "Grade";
  comboColumn.HeaderText = "Grade";
  comboColumn.ValueMember = "Grade";
  comboColumn.DisplayMember = "Grade";
  dataGridView1.Columns.Add(comboColumn);
  dataGridView1.Columns.Add("ID", "ID");
}

private void AddRows() {
  int newRowIndex = dataGridView1.Rows.Add();
  dataGridView1.Rows[newRowIndex].Cells[1].Value = 1;
  newRowIndex = dataGridView1.Rows.Add();
  dataGridView1.Rows[newRowIndex].Cells[1].Value = 2;
  newRowIndex = dataGridView1.Rows.Add();
  dataGridView1.Rows[newRowIndex].Cells[1].Value = 3;
}

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  try {
    if (e.ColumnIndex == 1) {
      if (dataGridView1.Rows[e.RowIndex].Cells[1].Value != null) {
        DataGridViewComboBoxCell comboCell = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewComboBoxCell;
        if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() == "1") {
          SetCombo(1, comboCell);
        } else {
          if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() == "2") {
            SetCombo(2, comboCell);
          } else {
            SetCombo(3, comboCell);
          }
        }
      }
    }
  }
  catch (Exception ex) {
    MessageBox.Show("Error: " + ex.Message);
  }
}

private void SetCombo(int comboType, DataGridViewComboBoxCell comboCell) {
  comboCell.Value = "";
  comboCell.Items.Clear();
  if (comboType == 1) {
    comboCell.Items.Add("A");
    comboCell.Items.Add("B");
    comboCell.Items.Add("C");
    return;
  }
  if (comboType == 2) {
    comboCell.Items.Add("D");
    comboCell.Items.Add("E");
    comboCell.Items.Add("F");
    return;
  }
  comboCell.Items.Add("A");
  comboCell.Items.Add("B");
  comboCell.Items.Add("C");
  comboCell.Items.Add("D");
  comboCell.Items.Add("E");
  comboCell.Items.Add("F");
}