简体   繁体   English

C#和SQL System.ArgumentOutOfRangeException

[英]C# and SQL System.ArgumentOutOfRangeException

I am attempting to create an application which connects to a database using sql and I am trying to create a dataview which looks at the current selected dataview and then pulls back information from another table. 我试图创建一个使用sql连接到数据库的应用程序,并且试图创建一个dataview,它查看当前选定的dataview,然后从另一个表中拉回信息。 I have followed some guides and have gotten fairly close but I am currently getting this error: 我遵循了一些指南,并且已经相当接近了,但是我目前遇到此错误:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Index was out of range. mscorlib.dll中发生了'System.ArgumentOutOfRangeException'类型的未处理异常。其他信息:索引超出范围。 Must be non-negative and less than the size of the collection. 必须为非负数并且小于集合的大小。

Any help would greatly be appreciated. 任何帮助将不胜感激。 (Visual Studio shows the error at the end of the first line below) (Visual Studio在下面第一行的末尾显示错误)

string PersonID = Grid1.SelectedRows[0].Cells[0].Value.ToString();
sqlDataAdapter2.SelectCommand.CommandText = "select * from Personal_Emails where PersonID=" + PersonID;
sqlDataAdapter2.Fill(dataSet21.Personal_Emails);

Have you checked that SelectedRows & Cells have a selected value? 您是否检查过SelectedRowsCells是否具有选定值? You could use the debugger and see what the values are. 您可以使用调试器并查看值。

Also: 也:

You are defining PersonID as a string. 您正在将PersonID定义为字符串。 Is it a string value in your database? 它是数据库中的字符串值吗? If so, have you tried: 如果是这样,您是否尝试过:

sqlDataAdapter2.SelectCommand.CommandText = "SELECT * FROM Personal_Emails WHERE PersonID='" + PersonID + "'";

You need to check if something exists before you can use it. 您需要先检查是否存在某些物品,然后才能使用它。

var selectedRow = Grid1.SelectedRows[0];
var cell = selectedRow == null ? false : selectedRow.Cells.Any();
var personID = (cell) ? Grid1.SelectedRows[0].Cells[0].Value.ToString() : "";

if(!string.isNullOrEmpty(personID)
    // do query stuff
string PersonID = Grid1.SelectedRows[0].Cells[0].Value.ToString();

verify if this line is returning some value <> null. 验证此行是否返回某些值<> null。

example : if the grid has no selected rows it will return error or empty value. 示例:如果网格没有选定的行,它将返回错误或空值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM