简体   繁体   中英

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. 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. 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)

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? You could use the debugger and see what the values are.

Also:

You are defining PersonID as a string. 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.

example : if the grid has no selected rows it will return error or empty value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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