C# 使用datagridview和dropdownlist进行操作
这是我表格的图像 应该这样做。C# 使用datagridview和dropdownlist进行操作,c#,winforms,C#,Winforms,这是我表格的图像 应该这样做。 1.用户将选择要重命名的项目。(例如,用户选择“string1”) 2.在下拉列表中选择新项目名称。(例如,用户选择“新字符串1”) 注意:下拉列表中的选定项将是“string1”的新名称 3.单击按钮。(单击按钮后。这将自动创建所做的更改。) 问题是: 如何从下拉列表中的选定项更改datagridview中的项名称 这是我的一些代码。 public void loadgrid() { DataGridViewCheckB
1.用户将选择要重命名的项目。(例如,用户选择“string1”)
2.在下拉列表中选择新项目名称。(例如,用户选择“新字符串1”)
注意:下拉列表中的选定项将是“string1”的新名称
3.单击按钮。(单击按钮后。这将自动创建所做的更改。) 问题是:
如何从下拉列表中的选定项更改datagridview中的项名称 这是我的一些代码。
public void loadgrid()
{
DataGridViewCheckBoxColumn checkboxColumn = new DataGridViewCheckBoxColumn();
checkboxColumn.Width = 25;
dataGridView1.Columns.Add(checkboxColumn);
DataGridViewTextBoxColumn textboxcolumn = new DataGridViewTextBoxColumn();
textboxcolumn.Width = 150;
dataGridView1.Columns.Add(textboxcolumn);
dataGridView1.Rows.Add(new object[] { false, "string1" });
dataGridView1.Rows.Add(new object[] { false, "string2" });
}
用于按钮1
private void button1_Click(object sender, EventArgs e)
{
int x = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.TrueValue = true;
if(chk.Value == chk.TrueValue) // there no chk.Check on datagridview just chk.Selected
{
//code here
//this will test if the checkbox has been checked.
//the selected item on the dropdown will be the
//new name of the item on the datagridview
}
}
x = x + 1;
}
我认为,如果要使用复选框更改行中的所有字符串,这将有所帮助:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
DataGridViewCheckBoxCell chk1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk1 != null && chk1.Value!=null && (bool)chk1.Value) // there no chk.Check on datagridview just chk.Selected
{
string newString = string.Empty;
if (comboBox1.SelectedItem != null)
{
newString = comboBox1.SelectedItem.ToString();
row.Cells[dataGridView1.Columns.Count - 1].Value = newString;
}
}
}
}
如果只想更改选中复选框的选定行中的字符串,则可以使用以下代码:
if(dataGridView1.SelectedRows.Count>0)
{
DataGridViewRow row = dataGridView1.SelectedRows[0];
if (!row.IsNewRow)
{
DataGridViewCheckBoxCell chk1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk1 != null && chk1.Value!=null && (bool)chk1.Value) // there no chk.Check on datagridview just chk.Selected
{
string newString = string.Empty;
if (comboBox1.SelectedItem != null)
{
newString = comboBox1.SelectedItem.ToString();
row.Cells[dataGridView1.Columns.Count - 1].Value = newString;
}
}
}
}
如果您想设置所有选定的行(如果在
DataGridView
控件中可以设置,那么只需迭代SelectedRows
属性我在发布之前检查了代码,它工作正常。您的错误具体在哪里?在(bool)上有错误-对象引用未设置为对象的实例。我也尝试了此方法。bool b=true;然后将(bool)更改为(b)chk1.value,但仍然存在错误。现在检查一下,我更改了代码,但我认为您在将任何内容插入DataGridView之前调用了此方法。