【发布时间】:2013-07-30 11:23:48
【问题描述】:
我有这段代码,但是当我点击列表框中的一条记录时,我遇到了这个错误:
System.NullReferenceException
这是我的代码:
namespace CestovniPrikaz
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=(Loca..Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{ InitializeComponent();
loadlist(); }
private void Form2_Load(object sender, EventArgs e)
{ cmd.Connection = cn;
loadlist(); }
private void loadlist()
{ listBox1.Items.Clear();
cmd.Connection = cn;
cn.Open();
cmd.CommandText = "select Name from Person";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
} }
cn.Close(); }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedValue = l.SelectedIndex;
txtName.Text = listBox1.SelectedValue.ToString();
}} } }
问题大概出在这一行:
txtName.Text = listBox1.SelectedValue.ToString();
请问你有什么想法吗?
【问题讨论】:
-
我在这里复制,因为我有错误:帖子主要是代码......在我的代码中我有正常的;)
-
表单加载时列表框中是否有项目?
-
首先请确定您的错误在哪里,使用调试器来执行此操作。
-
是的,我在列表框中有所有记录...加载列表正常...
-
哪一行报错了?