Q:
I have a gridview ,and i try to delete some record , I store my primary keys in DataKeyNames
.
my question has two parts :
1-The following code make an exception, I don't know the reason:
protected void gv_courses_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
ICollection keys = gv_moreCour开发者_开发问答ses.DataKeys[index].Values;
//////the rest of the code.
}
catch (Exception ee)
{
string message = ee.Message;
}
}
my aspx:
DataKeyNames="permission_code,lect_code,note_title,iscourse"
<asp:ImageButton ID="btn_Delete" runat="server" CausesValidation="False" ImageUrl="~/Images/Symbols-Delete-icon.png"
CommandArgument='<%#((GridViewRow)Container).RowIndex%>' CommandName="deleteCourse" />
The exception is:in this line gv_moreCourses.DataKeys[index];
System.ArgumentOutOfRangeException
2- If i solve the first problem how to access each value in my keys
.prefer LINQ
.
It looks like in the RowCommand
event for a GridView called gv_courses
, you are taking the index and then referencing another GridView called gv_moreCourses
to grab the key. If gv_courses
has more rows than gv_moreCourses
(or gv_moreCourses
doesn't have a defined key), then you will get an error from clicking on one of the latter row indexes that don't exist on the second Grid. Did you intend for that to say this instead?
ICollection keys = gv_courses.DataKeys[index].Values;
^^^^ remove "more"
Edit The return type of DataKeys.Values
is actually System.Collections.Specialized.IOrderedDictionary
, which contains an indexer and properties .Keys
and .Values
for easy access to the contents of the key:
IOrderedDictionary keys = gv_courses.DataKeys[index].Values;
^^^^ change ICollection to IOrderedDictionary
keys[0] ... // permission_code
keys[1] ... // lect_code
keys[2] ... // note_title
keys[3] ... // iscourse
Does the error come on the line where you index the table? This seems to be an indexing bug. Are you giving the values of index from correct range? It can be that your other part of program starts indexes from 1 and this parts need them to start from 0.
This came to my mind at first view without looking more deeply to your problem.
int index = Convert.ToInt32(e.CommandArgument);
Index will have the value of the Selected Data Key, like it can have different value than 0
, Since it will require DataKey Index gv_moreCourses.DataKeys[DataKey]
You can directly get the value from e.CommandArgument
. It will return the Selected Row Data key value
OR, you can get it by passing in the name of the DataKey Name, e.g. gv_moreCourses.DataKeys["NameofDataKey"].Values;
精彩评论