开发者

update a listbox item

开发者 https://www.devze.com 2023-04-12 08:40 出处:网络
i want from my program to select a listbox item and then update it.i have a list ecoItems.Eco is a class with 2 store variables,one string and one double variable.SetEcoValues is a set Method take two

i want from my program to select a listbox item and then update it.i have a list ecoItems.Eco is a class with 2 store variables,one string and one double variable.SetEcoValues is a set Method take two values,one string and one double.i try this code but don't change anything.any suggestions?

         private void Update_Click(object sender, EventArgs e)
    {


            Eco y;
            y = ecoItems.ElementAt<Eco>(listBox1.SelectedIndex);
            y.SetEcoValues(textBox1.Text,Convert.ToDouble(textBox2.Text))开发者_如何学运维;
            listBox5.Items.Insert(listBox1.SelectedIndex, y);
        }


    }


Using your code and what I would guess is your class, I'd do something like this:

class Eco {
  public Eco() { }
  public void SetEcoValues(string text, double value) {
    Text = text;
    Value = value;
  }
  public string Text { get; set; }
  public double Value { get; set; }
  public override string ToString() {
    if (!String.IsNullOrEmpty(Text)) {
      return Text;
    }
    return base.ToString();
  }
}

ListView listView1; // initialized somewhere, I presume.

void Update_Click(object sender, EventArgs e) {
  if ((listView1.SelectedItems != null) || (0 < listView1.SelectedItems.Count)) {
    ListViewItem item = listView1.SelectedItems[0];
    Eco y = item.Tag as Eco;
    if (y == null) {
      y = new Eco();
    }
    y.SetEcoValues(textBox1.Text, Convert.ToDouble(textBox2.Text));
    item.Text = y.Text;
    if (item.SubItems.Count < 2) {
      item.SubItems.Add(y.Value.ToString());
    } else {
      item.SubItems[1].Text = y.Value.ToString();
    }
    item.Tag = y;
  }
}


You're not actually getting the ListItem anywhere, and trying to add something to the ListBox which isn't a ListItem. You could try something like so:

ListItem Item = listBox1.SelectedItem;

//Update the Text and Values
Item.Text = textBox1.Text,;
Item.Value = textBox2.Text;

Or... if you have the ListBox Bound to your list of Ecos and want it updated, instead of listBox5.Items.Insert... you would need to re bind it.

listBox5.DataSource = y;
listBox5.DataBind();
0

精彩评论

暂无评论...
验证码 换一张
取 消