繁体   English   中英

在 DataGridView 中添加 ComboBox 列

[英]Adding a ComboBox column in DataGridView

我正在使用 winform datagridview 控件来添加、编辑和删除 MS Access 数据库中的记录。 当没有 pk-fk 关系时,它工作得很好。 现在我想在 UserDetails 表中添加一个 UserTypeId 列。 UserTypeId 来自 UserTypes 表。

Table: UserDetails
--------------------------------------
UserId | UserTypeId | Other fields...|
--------------------------------------
       |            |                |
--------------------------------------

Table: UserTypes
---------------------------
UserTypeId | UserTypeName |
---------------------------
           |              |
---------------------------

这些是我现有的代码-

public partial class frmUser : Form
{
    private String connectionString = null;
    private OleDbConnection connection = null;
    private OleDbDataAdapter da = null;
    private OleDbCommandBuilder commandBuilder = null;
    private DataTable dataTable = null;
    private BindingSource bindingSource = null;
    private String selectQueryString = null;

    public frmUser()
    {
        InitializeComponent();
    }

    private void frmUser_Load(object sender, EventArgs e)
    {
        connectionString = GlobalVariables.ConnectionString;// ConfigurationManager.AppSettings["connectionString"];
        connection = new OleDbConnection(connectionString);
        selectQueryString = "SELECT * FROM UserDetail";

        connection.Open();

        da = new OleDbDataAdapter(selectQueryString, connection);
        commandBuilder = new OleDbCommandBuilder(da);

        dataTable = new DataTable();
        da.Fill(dataTable);
        bindingSource = new BindingSource();
        bindingSource.DataSource = dataTable;

        dataGridViewTrial.DataSource = bindingSource;

        // if you want to hide Identity column
        dataGridViewTrial.Columns[0].Visible = false;
    }

    private void addUpadateButton_Click(object sender, EventArgs e)
    {
        try
        {
            da.Update(dataTable);
        }
        catch (Exception exceptionObj)
        {
            MessageBox.Show(exceptionObj.Message.ToString());
        }
    }

    private void deleteButton_Click(object sender, EventArgs e)
    {
        try
        {
            dataGridViewTrial.Rows.RemoveAt(dataGridViewTrial.CurrentRow.Index);
            da.Update(dataTable);
        }
        catch (Exception exceptionObj)
        {
            MessageBox.Show(exceptionObj.Message.ToString());
        }
    }
}

如何使用上述代码添加查找列? 谢谢你。

您需要2个BindingSource ,一个BindingSource将连接到您的UserDetails表(已经完成),而其他将连接到UserTypes表。

然后,您需要将第二个BindingSource附加到DataGridViewDataGridViewComboBoxColumn

dataGridViewTrial.DataSource = bindingSource;
// after you are binding your DataGridridView

// assuming that the UserTypeId Column is at 1st index
var colUserTypes = this.dataGridViewTrial.Columns[1];
// by default columns are added as Text columns
// so we are removing the auto added column
this.dataGridViewTrial.Columns.Remove(colUserTypes);

// creating new combobox Column
var cmbColumn = new DataGridViewComboBoxColumn();
cmbColumn.DataPropertyName = "UserTypeId";      // this is the property in UserDetails table
cmbColumn.ValueMember = "UserTypeId";           // this is the property in UserTypes table
cmbColumn.DisplayMember = "UserTypeName";       // again this property is in UserTypes table
cmbColumn.DataSource = userTypesBindingSource;  // this binding source is connected with UserTypes table
this.dataGridViewTrial.Columns.Add(cmbColumn);

通常,使用设计模式可以更轻松地完成此操作。 您可以在Google上搜索,我想这里有很多可用的走廊。

您如何在datagridview中生成列? 如果列是动态生成的,则必须在网格中进行更改,然后首先手动创建所有列,然后在每个DataGridView列的DataPropertyName中分配数据库字段名称。 现在,将列类型DataGridViewComboboxColumn分配给UserTypeId列。

完成上述所有过程后,需要在绑定DataGridView之前填充该列。

string _SQL = "Select UserTypeId,UserTypeName From UserTypes Order By UserTypeName";
//Dont include Order By UserTypeName if you have created clustered index on it.

SqlDataAdapter Da = New SqlDataAdapter(_SQL, Connection);
DataTable Dt = New DataTable();
Da.Fill(Dt);

DataGridViewComboBoxColumn colUserTypeId = (DataGridViewComboBoxColumn)DataGridView1.Columns["UserTypeId"];

colUserTypeId.DisplayMember = "UserTypeName";
colUserTypeId.ValueMember = "UserTypeId";

colUserTypeId.DataSource = Dt;

//CODE TO FILL GRIDVIEW

现在,您的网格将在UserTypeID列中填充用户类型。 应用程序将从DataGridView1.Rows[RowIndex].Cells["UserTypeID"].Value属性返回UserTypeID

我看到这个问题已经有了答案,但是如果我还想查看DataGridViewComboBoxColumn中所有UserTypes的列表怎么办?

我们这样做如下:

  1. 您需要来自每个Table的 2 个单独的Queries 对于第一个,我们有:
SELECT UserId, -- cellindex 0
    UserTypeID, -- cellindex 1
    UserTypeID.UserTypeName -- cellindex 2
From UserDetails  
    INNER JOIN UserTypes ON UserDetails.UserTypeID = UserTypes.UserTypeId
Order By UserTypeName
-- WHERE Conditions are applied
  1. 对于第二个Query ,您必须这样做:
SELECT 
    UserTypeId,
    UserTypeName
FROM UserTypes 
-- WHERE CONDITIONS ARE APPLIED
  1. 现在对于下一部分,您将使用此查询来填充您的combobox项目。 像下面的代码:
// After filling your DataSet with the aforementioned query at part(2) you need to create a column for that
DataGridViewComboBoxColumn cmbx_clm = new DataGridViewComboBoxColumn();
cmbx_clm.Name = "UserTypesCmbx";
cmbx_clm.HeaderText = "User Types";

// Uncomment the lines below if  you want
//cmbx_clm.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
//cmbx_clm.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

// Now Let's bind the cmbx_clm DataSource to the DataSet/DataTable that we named it CreatedDs
cmbx_clm.DataSource = createdDs.Tables[0]; 

// Pay attention to the following lines because it gets tricky
cmbx_clm.ValueMember = "UserTypeId";
cmbx_clm.DisplayMember = "UserTypeName";

// Now let's add the Column to the DataGridView
Users_GRD.Columns.Add(cmbx_clm); // cellindex 3

// For the beauty of our grid we hide the extra column that we do not need
Users_GRD.Columns[2].Visible = false;

// Now in order to show the "UserTypeName" in the combobox and also corresponding to the first query 

foreach(DataGridViewRow row in Users_GRD.Rows)
{
   // We add UserTypeID VALUE to the combobox ValueMember
    row.Cells[3].Value = row.Cells[1].Visible
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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