在两个列表框之间移动值 [英] Moving values between two listboxes

查看:62
本文介绍了在两个列表框之间移动值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个列表框中选择项目,然后单击按钮将它们添加到第二个列表框中.问题是当我想从列表框2中取消选择选定的项目时,它给出了对象引用未设置为对象实例"的错误下面是我在SELECT按钮后面添加的代码.我使用了相同的代码来将listbox1替换为listbox2,反之亦然.

注意:正在从数据库中检索listbbox1中的项目.并且在listbox2中选择的itmes将保存到databse

I m selecting items from one listbox and adding them to second listbox on button click.the problem is tht when i want to deselect the selected items from listbox2, it gives "Object reference not set to an instance of an object" error.Below is the code I added behind SELECT button.I have used the same code for deselting with listbox1 replaced by listbox2 and vice versa.

NOTE: items in listbbox1 are being retrieved from database. and itmes tht got selected in listbox2 will be saved to databse

List<int> rowIndexes = new List<int>();

foreach (int index in listBox1.SelectedIndices)
{
    DataRowView view = listBox1.Items[index] as DataRowView;

    string id = view["Course_Id"].ToString();

    string name = view["Course_Name"].ToString();

    listBox2.Items.Add(name);

    rowIndexes.Add(index);

}

try
{
    for (int i = rowIndexes.Count; i > 0; i--)
    {
       dt.Rows.RemoveAt(rowIndexes[i - 1]);

       dt.AcceptChanges();
    }

}
catch (Exception er)
{
     MessageBox.Show(er.Message);
}


任何帮助将不胜感激.


Any help would be appreciated.

推荐答案

您知道称为"Debugger"的魔术工具吗?您的按钮单击代码,然后查看所分配的值在哪里为空.这就是引发该错误的原因.
Do you know the magic tool called "Debugger" :) use it and will be amaze by the results.. use the Debugger in your button click code and see where the value that you are assigning is null. that''s why it is throwing that error.


List<int> row Indexes = new List<int>();


这行甚至都不会编译.
因此,请确保您已在此处复制粘贴了正确的代码.


This line wont even compile.
So make sure you have copy pasted the right code here. This will help someone assist you better.


foreach (int index in listBox1.SelectedIndices)
{
DataRowView view = listBox1.Items[index] as DataRowView;

string id = view["Course_Id"].ToString();

string name = view["Course_Name"].ToString();

listBox2.Items.Add(name);

rowIndexes.Add(index);

}



您在那里遇到了一个问题.您对rowindexes变量的赋值应该返回null.因此,当您尝试达到它时,您将遇到异常.请使用MessageBox.Show(index);检查索引值;首先使用方法.



You have an issue there.Your assignment on rowindexes variable should return null.So when you try to reach it you ''ve got an exception.Check your index value with a MessageBox.Show(index); Method first.


这篇关于在两个列表框之间移动值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆