我想基于组合框选择获取或设置数据到DataGridView的每个单元格

时间:2013-03-16 19:39:47

标签: c# sql-server-2008

请找到我的代码,我需要知道组合框选择和datagridview之间的关系。基本上,如果我设置我的区域选择,那么只有那些与区域相关的内容才会显示,而不是现在我正在显示的整个数据库。感谢。

        private void RTUModification_Load(object sender, EventArgs e) {
        //Select cell where checkbox to be display
        Rectangle rect = this.rtumodDGV1.GetCellDisplayRectangle(0, -1, true);   
        chkbox.Size = new Size(18, 18);

        //set position of header checkbox where to places
        rect.Offset(4, 2);
        chkbox.Location = rect.Location;

        chkbox.CheckedChanged += rtucheckBoxCheckChanged;

        //Add CheckBox control to datagridView
        this.rtumodDGV1.Controls.Add(chkbox);

        // Create new DataTable instance
        dtDataTable = new System.Data.DataTable();
        if (null == dtDataTable)
        {
            MessageBox.Show("Insufficient memory.", "ERROR");
        }
        //load the datable and fill them with value
        strErrorMsg = Utilities.OpenSQLConnection(out m_SqlConn, true, false);   //load normal database
        if (false == string.IsNullOrEmpty(strErrorMsg))
        {
            MessageBox.Show(strErrorMsg, "SQL connection ERROR");
        }

        SqlDataAdapter sqlAdapter = null;
        strSelectCmd = "SELECT Area_ID, StationId, SystemId, CCNumber, LineNumber, RTUNumber, SRTUNumber, Description, SDescription FROM RTU_ADDRESS";
        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.Connection = m_SqlConn;
        sqlCmd.CommandText = strSelectCmd;
        sqlAdapter = new SqlDataAdapter();
        sqlAdapter.SelectCommand = sqlCmd;
        strErrorMsg = Utilities.FillDataTable(m_SqlConn, strSelectCmd, dtDataTable);
        if (string.IsNullOrEmpty(strErrorMsg) == false)
        {
            MessageBox.Show("Failed to retrieve information from database.", "ERROR");
            dtDataTable.Dispose();
            Utilities.CloseAndDisposeSQLConnection(m_SqlConn);
        }
        int iRetrievedNoOfRecords = dtDataTable.Rows.Count;
        if (iRetrievedNoOfRecords > 0)
        {

            for (int i = 0; i < iRetrievedNoOfRecords; i++)
                this.rtumodcomboBox.Items.Add((string)dtDataTable.Rows[i]["Area_ID"]);
        }
        strErrorMsg = Utilities.ExecuteSQLCommand(m_SqlConn, strSelectCmd);
        if (string.IsNullOrEmpty(strErrorMsg) == false)
        {
            MessageBox.Show(this, "Error!Loading into RTU datagrid");
        }

        //load the datagridview header
        rtumodDGV1.DataSource = dtDataTable;         
    }

1 个答案:

答案 0 :(得分:0)

以下是您可能需要的示例代码。

  strSelectCmd = "SELECT Area_ID, StationId, SystemId, CCNumber, LineNumber, RTUNumber, SRTUNumber, Description, SDescription FROM RTU_ADDRESS where Area_ID="+cbxMyCombox.SelectedIndex;

其他SelectedIndex的其他选项可以是SelectedItem或SelectedValue。取决于您使用的是什么。现在还不清楚。