exception - getting error when trying to read from DataGridView with event handler winform -


i have winform has gridview applying data via dataset. when data binds, calls selectionchanged event handler. researched , found way around adding if clause see if dgv has focus (all other resolutions did not work found). part working planned. when step through program, event handler tries go through code 3 times when binds data. if clause stops reaching code. issue after data binds , choose row in dgv, event handler throws "an unhandled exception of type 'system.argumentoutofrangeexception' occurred in mscorlib.dll". when stepping through code, dgv returning proper row index 'int row' variable, code use row/cell info throws error before applies 'loadtableid' variable. need help. can ignore second dgv in top. takes selected row's info , gets db table info. also, if helps, did not apply datasource program or create datasets each individual dataset returned, using system's generic dataset when returning data.

     private void gvmainselectresults_selectionchanged(object sender, eventargs e)     {         if (gvmainselectresults.focused)         {             gvmainarchiveresults.datasource = null;  //second dgv populated later , everytime cleared new selection              loadtableid = 0;             orgid = 0;             dbfilename = "";             sourcetype = "";              int row = gvmainselectresults.currentcell.rowindex;             loadtableid = convert.toint32(gvmainselectresults.selectedrows[row].cells["loadtableid"].value);  //this error, if "int row" has correct index number             orgid = convert.toint32(gvmainselectresults.selectedrows[row].cells["organizationid"].value);             dbfilename = convert.tostring(gvmainselectresults.selectedrows[row].cells["filename"].value);             sourcetype = convert.tostring(gvmainselectresults.selectedrows[row].cells["sourcetype"].value);              more code here... 

you using rowindex value text selectedrows collection.
collection contains only

gets collection of rows selected user.

this means collection contains subset of rows present in grid. when rowindex 2 , have 1 row in selectedrows collection outofrange exception.

with rowindex value should refer rows collection instead

loadtableid = convert.toint32(gvmainselectresults.rows[row].cells["loadtableid"].value); orgid = convert.toint32(gvmainselectresults.rows[row].cells["organizationid"].value); dbfilename = convert.tostring(gvmainselectresults.rows[row].cells["filename"].value); sourcetype = convert.tostring(gvmainselectresults.rows[row].cells["sourcetype"].value); 

Comments