当我尝试从数据库中检索数据时,出现此错误“索引0为负或高于行数" [英] when i try to retrieve data from a database i get this error 'index 0 is either negative or above rows count'
问题描述
private void txtUser_TextChanged(object sender, EventArgs e)
{
SqlDataAdapter dau = new SqlDataAdapter("select privilege from users where username='"+txtUser.Text+"'",con);
DataSet dsu = new DataSet();
dau.Fill(dsu,"users");
DataView dvu = new DataView(dsu.Tables["userd"]);
txtUsername.Text = dvu[0]["privilege"].ToString();
}
添加了代码块[/编辑]
Code block added[/Edit]
推荐答案
您的DataView似乎没有行:
It appears that your DataView has no rows:
txtUsername.Text = dvu[0]["privilege"].ToString();
您可以在访问行集合(或任何与此相关的索引集合)之前执行以下操作来检查这种情况:
You can check for this condition by doing the following before you access the rows collection (or any indexed collection for that matter):
if(dvu.Count > 0)
{
txtUsername.Text = dvu[0]["privilege"].ToString();
}
另外,以下几行确实很危险:
Also, the following line is really dangerous:
SqlDataAdapter dau = new SqlDataAdapter("select privilege from users where username='"+txtUser.Text+"'",con);
通过将未经过处理的用户输入串联到SQL字符串中,您完全可以接受SQL注入.您可以通过参数化查询来解决此问题.
https://www.owasp.org/index.php/SQL_Injection [ http://msdn.microsoft.com/en-us/library/system. data.sqlclient.sqlparameter.aspx [ ^ ]
You''re completely open to SQL injection by concatenating unsanitized user input into a SQL string. You can combat this by parameterizing your queries.
https://www.owasp.org/index.php/SQL_Injection[^]
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx[^]
DataView dvu = new DataView(dsu.Tables["userd"]);
您确定不应该是userid
吗?
Are you sure that should not be userid
?
这篇关于当我尝试从数据库中检索数据时,出现此错误“索引0为负或高于行数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!