在DataGridView中添加ComboBox列

时间:2014-07-13 13:33:32

标签: c# winforms 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 个答案:

答案 0 :(得分:1)

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

然后,您需要将第二个BindingSource附加到DataGridView' s DataGridViewComboBoxColumn

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上搜索我猜有很多aricle可以做到这一点。

答案 1 :(得分:1)

如何在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列中的用户类型。应用程序将从UserTypeID属性返回DataGridView1.Rows[RowIndex].Cells["UserTypeID"].Value