C# C从文本框更新选定的组合框项目名称
我想通过更改文本框名称来更新comboBox selectedItem name。在不丢失combobox值的情况下,如何实现它C# C从文本框更新选定的组合框项目名称,c#,winforms,combobox,C#,Winforms,Combobox,我想通过更改文本框名称来更新comboBox selectedItem name。在不丢失combobox值的情况下,如何实现它 private void addItem_Click(object sender, EventArgs e) { nameItem.Enabled = true; nameItem.Text = "Item " + counter.ToString(); nameItem.Focus(); comboBox1.Items.Add(nam
private void addItem_Click(object sender, EventArgs e)
{
nameItem.Enabled = true;
nameItem.Text = "Item " + counter.ToString();
nameItem.Focus();
comboBox1.Items.Add(nameItem.Text);
comboBox1.SelectedItem = nameItem.Text;
counter++;
}
private void nameItem_TextChanged(object sender, EventArgs e)
{
????????
}
最好先更新源代码,然后再绑定它。 也试试这个
private void nameItem_TextChanged(object sender, EventArgs e)
{
string value = nameItem.Text;
var list = (List<KeyValuePair<String, String>>)comboBox1.DataSource;
list.Add(new KeyValuePair<string, string>(value,value));
comboBox1.DataSource = list;
comboBox1.DataBind();
}
这是一个简单的,它的工作,但它可能有点长 这里我有一个组合框,textBox1和按钮,用于向组合框添加值, 和文本框2,用于编辑所选项目
string[] items = new string[99];
int a = 0;
int i = 0;
private void button1_Click(object sender, EventArgs e)
{
items[i] = textBox1.Text;
i++;
comboBox1.Items.Clear();
for (int n = 0; n < items.Length; n++) {
if(items[n] != null) comboBox1.Items.Add(items[n]);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
a = comboBox1.SelectedIndex;
MessageBox.Show(a.ToString());
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
items[a] = textBox2.Text;
comboBox1.Items.Clear();
for (int n = 0; n < items.Length; n++)
{
if (items[n] != null) comboBox1.Items.Add(items[n]);
}
}
工作原理:我们有一个项目数组和两个整数变量。一个用于添加项目的计数,另一个用于选定项目索引
按钮1只是添加新项目,清除所有项目并再次更新em
当您编辑textbox2的文本时,它将更新“items”数组中的项目,然后更新组合框ez
编辑:没有看到winform标记-这将不起作用-将离开以防任何ASP人员遇到
public void TextBox1_OnTextChanged(object sender, EventArgs e)
{
ddl.DataSource = null;
ddl.DataBind();
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = (from ListItem b in ddl.Items
select b.Selected ? new ListItem(TextBox1.Text, b.Value) : b).ToList();
ddl.DataBind();
}
ddl是下拉框的名称
Textbox1是文本框的名称
这将更改所选项目的名称。如果您需要更多代码,请在评论中告诉我。谢谢您的时间和友好的回答。 我解决了下面的问题
private void addItem_Click(object sender, EventArgs e)
{
nameItem.Enabled = true;
comboBox1.Items.Add("Item " + counter.ToString());
comboBox1.SelectedItem = "Item " + counter.ToString();
nameMacro.Text = "Item " + counter.ToString();
//comboBox1.SelectedItem = nameItem.Text;
//nameItem.Focus();
// Ad degistirme -> comboBox1.Items[comboBox1.FindStringExact("string value")] = "New Value";
counter++;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
comboBox1.Items[comboBox1.SelectedIndex] = nameItem.Text;
}
最好是更新源代码,然后重新绑定组合框…WinForms不使用数据绑定。