我收到此错误“索引0为负数或高于行帐户”在运行下面的代码时 [英] I got this error "index 0 is either negative or above rows account" while running the code below

查看:80
本文介绍了我收到此错误“索引0为负数或高于行帐户”在运行下面的代码时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void txtDesc_TextChanged(object sender, EventArgs e)
       {
      SqlDataAdapter dap = new SqlDataAdapter("select partnumber from movement where     description=('"+txtDesc.Text+"')",con);
           DataSet dsp = new DataSet();
           dap.Fill(dsp, "movement");
           DataView dvp = new DataView(dsp.Tables["movement"]);
           txtPartno.Text = dvp[0]["partnumber"].ToString();
       }

推荐答案

错误行是(可能):



Error line is (possibly):

txtPartno.Text = dvp[0]["partnumber"].ToString();





您的查询返回没有行,因此表没有行,因此视图没有行,因此dvp [0]对应没有行。结果,你手上有一个例外。



但我认为实际问题是你的实施。如果此事件处理程序用于TextBox,则只要用户按下某个键,该代码就会运行。例如,如果您打算编写描述,当您按下a键时,您的查询将运行 description =('a')哪些(可能)返回没有行。



一些建议:

1-设计多层应用程序(设计一个单独的数据管理类)

2-将您的UI处理代码包含在'try catch'结构中,以避免未处理的异常和完全崩溃。

3-使用调试器来跟踪代码。



Your query returns no row, therefore table has no row, therefore view has no row, therefore dvp[0] corresponds to no row. As a result, you have an exception in your hand.

But I think the actual problem is your implementation. If this event handler is for a TextBox, then whenever user presses a key, that code runs. For example, if you intend to write "a description", when you press key 'a', your query runs for description=('a') which (possibly) returns no row.

Some advices:
1- design multitier application (design a separate class for data management)
2- enclose your UI handling codes in a 'try catch' structure to avoid 'unhandled exception' and a total crash.
3- use the debugger to trace your code.


添加此行



Add this line

  if(dvp.Count > 0)
txtPartno.Text = dvp[0]["partnumber"].ToString();









or

DataTable dt = new DataTable();
           dap.Fill(dt);
           if(dt.Rows.Count > 0)
           txtPartno.Text = dt.Rows[0]["partnumber"].ToString();


这篇关于我收到此错误“索引0为负数或高于行帐户”在运行下面的代码时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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