Server response to user events in a GridView (…or anywhere)
On a web application I have, I
used the GridView control and binded it to some data source. Since all the data
needed to go through some process, I did all the binding through the
code-behind. I needed to add a column of checkboxes and have that column
editable to the user. More what, I wanted some server reaction when the user
triggers the CheckChanged event for every checkbox.
I searched the net for some
solutions, and found a lot, but all seemed too complicated and involved too
much code. So after a little brainstorming I came up with a simple workaround
of my own to this problem.
First, I have the GridView in the
aspx page :
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="false">
</asp:GridView>
And I have some
databinding in the code (in the Page_Load event) :
List<Gilly> listGilly = new List<Gilly>();
listGilly.Add(new Gilly("Gilly", true));
listGilly.Add(new Gilly("Barr", false));
GridView1.DataSource =
listGilly;
GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
BoundField bf = new BoundField();
bf.DataField = "Name";
bf.HeaderText = "Names";
GridView1.Columns.Add(bf);
BoundField chkbx = new BoundField();
bf.DataField = "Check";
bf.HeaderText = "Checked?";
GridView1.Columns.Add(chkbx);
GridView1.DataBind();
As you can see, I attached an EventHandler for the
RowDataBound event of the GridView control. This is so I can add the checkbox
manually to each row.
void GridView1_RowDataBound(object
sender, GridViewRowEventArgs e)
{
if
(e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox
cb = new CheckBox();
e.Row.Cells[1].Controls.Add(cb);
}
}
Now all what we need is to attach an
EventHandler to the checkbox controls and we're set…
Inside the GridView1_RowDataBound method I added :
cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
Now we just need to add the method
cb_CheckedChanged with whatever we want to happen, and that's it! …Almost...
There's no reason the checkbox will trigger this server side event, since
nothing in the client tells it to do so. So we need to add the correct client
event. You probably realized that every button with on OnClick server event you
add, automatically has the __doPostBack javascript code in it. This redirects
the application back to the server with a certain control ID to raise the
event.
So how do we add this?
Simple…
cb.Attributes["onclick"]
= Page.GetPostBackClientEvent(cb, "arg");
Instead of the "arg" string I passed, you can pass
any argument you want, and then pick it up server side…
Have fun :)