The answer you seek is simple and tricky. I had that problem too in my website project, so I surfed the internet for days and not found what I and you were needed.
One day I just thought about the problem alone and made experiments for hours and finally realized that the only easy way to know the column that the button was clicked is in the RowCommand event
of the GridView
in the CommandName property
of the GridViewCommandEventArgs
. More correctly probably and comfortable is to edit columns of GridView
through the design mode and replace your Command fields to Button fields.
You can give any string/text
you want to each button field in its CommandName
, so in the RowCommand
event you can know which was clicked. Button1
or Button2
, but you don't want to give these strings, because you request something that the buttons should select and give to you, so the CommandName
should be the word select, but it can be SELECT too and Select and selecT and etc.
The select command can be mention in the CommandName
in many forms, and still the system will recognize it. So for example if you have two Button fields in the GridView
, whose first CommandName
is simply select and the other is SELECT, then when any of them is clicked the RowCommand
event raises and
if (e.CommandName == "select")
{
Label1.Text = "You clicked first button";
}
else
{
Label1.Text = "You clicked second button";
}
and the SelectedDataKey
of your GridView
will contains the data you requested. What other people offered in their answer to differ in CommandName
by setting button one to select_one
and setting button two to select_two
will help you to know if either select_one
was clicked or other, but the SelectedDataKey
of your GridView
will remain null
or DataKey
instance that doesn't contain the information you need at all.
In other words, the buttons will not select any necessary information, so it is very important to follow my answer. It is the exact, perfect and great solution to your problem!