1

如何在数据库运行时在 DataGridView 的组合框中显示文本?

例如,如果下次我想在组合框列中显示该文本时,我要从 DataGridView 的组合框中更新数据库中的文本。

sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
selectQueryString = "SELECT Code,CompanyName,FinancialYearStart,FinancialYearEnd,UserName,RoleP FROM CompanyInformation";

sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);

bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;

dataGridView3.DataSource = bindingSource;
dataGridView3.Controls.Clear();

DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);


private void button10_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
    con.Open();

    // if (dataGridView3.Columns.Count >= 4 && dataGridView3.Columns.Count < 10)
    // {
        int i = dataGridView3.Rows.Count;
        int r = 0;

        for (int s = 0; s < i; s++)
        {
            try
            {
                string Role = dataGridView3.Rows[s].Cells[0].Value.ToString();
                int Cod = Convert.ToInt32(dataGridView3.Rows[s].Cells[1].Value.ToString());
                if (Role != "")
                {
                    SqlCommand cmd = new SqlCommand("update CompanyInformation SET RoleP=@Role where Code=@Cod", con);
                    cmd.Parameters.AddWithValue("@Cod", Cod);
                    cmd.Parameters.AddWithValue("@Role", Role);

                    r = cmd.ExecuteNonQuery();
                }
            }
            catch
            {
            }

        }

        if (r >= 1)
        {
            MessageBox.Show("Update Successful");
            SuperUser obj = new SuperUser();
            this.Hide();
            this.ParentForm.Hide();               
        }
4

1 回答 1

0

你可以这样做:

DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.Items.AddRange("Protected", "UnProtected");
comboboxColumn.HeaderText = "RoleP";
dataGridView3.Columns.Add(comboboxColumn);

在那之后检查

foreach (DataGridViewRow row in dataGridView3.Rows)
{
    (row.Cells[1] as DataGridViewComboBoxCell).Value = yourvalue;
}
于 2012-12-27T06:44:13.207 回答