2010年11月19日星期五

Handle UserControl raised event (2): Raising Timing

Following the last post: Handle UserControl raised event. We will have a look at the timing of such event raised.
The UserControl event raise timing depends how the event is implemented in the UserControl.
In the last post, we have a UserControl event “TextboxTextChanged” which is raise by a TextChanged event. So the timing will be the same as the TextChanged event of the TextBoxt control. That is, when the page is posted back to the sever (in the case of the text in TextBox has been changed).
If we raise the UserControl event TextboxTextChanged in the Page_Load of the UserControl:
protected void Page_Load(object sender, EventArgs e)
{
TextboxTextChanged(sender, e);
}

Then the TextboxTextChanged will be raised when the in a different time. This means the UserControl event doesn’t have to raise in a Control event but can be anywhere. I.e. Let’s say in our UserControl, we have a event:
public event EventHandler CheckFailed;

And this event will raise in the function DoSomeCheck:

public void DoSomeCheck(bool con)
{
if (!con)
CheckFailed("Reason", new EventArgs());
}

The logic can be complex but here only is an example. The event only raise in the case of fail.

Then you can handle the event in the main page which contains that UserControl. Such pattern can be useful when the things you do in case of check fail are related to the main page but you still want the UserControl has that Check function.

2010年11月16日星期二

Handle UserControl raised event

What is the need?

The scenario is I have a user control which contains a set of textboxes. When the text of a textbox is changed, I want handle this event in the page which contains the user control.

How to do this?

This could be done in 4 steps. 2 in the user control page(.ascx) and 2 in the main page(.aspx).
Step 1: In the .ascs.cs file, declare an EventHandler which will be pasted to the main page after the event in the user control raised.
public event EventHandler TextboxTextChanged;

Step 2: In the function which handles the raised event, in this case is a TextChanged event of a textbox. Assume we have a textbox “tb1” in the UserControl and we handle its TextChanged event in the function”tb1_TextChanged” (Note. AutoPostBack must be set to true):


<asp:TextBox ID="tb1" runat="server" ontextchanged="tb1_TextChanged" AutoPostBack="true"/>

All we need to do is pass the arguments in the TextChanged event to our TextboxTextChanged eventhandler and raise it:


protected void tb1_TextChanged(object sender, EventArgs e)
{
TextboxTextChanged(sender, e);
}

Step 3: Assume we have this UserCtrol in our page, to do so, you can just drag the .ascx page to the design view. You should have the similar two lines in the .aspx page:


<%@ Register src="Textboxes.ascx" tagname="Textboxes" tagprefix="uc2" %>

Another is in the <body>:


<uc2:Textboxes ID="ucTextboxes" runat="server" />

We need manually register the EventHandler we defined in the .axcx in the Page_Load function:


protected void Page_Load(object sender, EventArgs e)
{
// register the event handler for the control
ucTextboxes.TextboxTextChanged += new EventHandler(ucTextboxes_TextboxTextChanged);
}


VS 2010 should be able to help you finish the register after you typed “+=” (press Tab twice, the IS should show the hit).

Step 4: In the step, we create a function to handle the event we registered in the Page_Load:


void ucTextboxes_TextboxTextChanged(object sender, EventArgs e)
{
Label1.Text = ((TextBox)sender).Text;
}

Alternatively, you don’t have to manually register the Event like you do in Step 3 but register it like when you do so for a ordinary server control:


<uc2:Textboxes ID="ucTextboxes" runat="server"
OnTextboxTextChanged="ucTextboxes_TextboxTextChanged" />

In this case, the function must declare as “protected” in Step 4 (There is no “protected” in origin step 4).


Conclusion


The 4 steps are very clear and easy to remember. They are: declare EventHandler, raise event, register event and handle event.

2010年11月6日星期六

How to get DataKey, RowIndex or Row from a GridView row event


When using a GridView, it's very common to raise an event from a control inside the GridView and then handle it in the code behind file. In most cases, we need know which row that control is in and what is the row index or the values of DataKey in that row. In this article, we will look through several ways to do so. They may not be comprehensive or the best solution but should be able to deal with most situations.
The first two methods shows how to handle the Button like control (Implement IButtonControl) and deals with the events have a "Click" Nature. The last one shows how to handle any event raised by any control to retrieve the information you need.



1. Using the embedded "SELECT" command
This should be the most easy and convenient way to get the selected row.

To do so, you can tick the check box for a GridView in the Design View:



This will result the following codes in the .aspx file:

 <asp:CommandField ShowSelectButton="True" />
Another way is using a button in a template field and assign "SELECT" to its CommandName:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="SELECT" />
    </ItemTemplate>
</asp:TemplateField>
And then, you need to create and handle the "SelectedIndexChanged" event for the GridView.

To do so, first register the event in the GridView attributes tag:

<asp:GridView /*all other attributes*/
            onselectedindexchanged="GridView1_SelectedIndexChanged">
Then, handle it in the code behind file:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridView gv = (GridView)sender;
    DisplayIndexAndDatakey(gv.SelectedIndex.ToString(), gv.SelectedDataKey.Value.ToString());
}
The RowIndex and DataKey can be retrieved from the SelectedIndex and SelectedDataKey properties.

Using the "SELECT" command should be your first choice, but in some case you may not want to use the "select" or you've already used it and still want to have another button click event. How to achieve that?



2.Using the "RowCommand" event in the GridView
Let's say you need a button in each row and do something when click it. You cannot use the first method because it already has other usage.

GridView provides another event called "RowCommand" to deal with such situation.

First, we need to register the event to the GridView. You can do this in the design view:



Or just do it like we register the "SELECT" event in method 1:

<asp:GridView /*all other attributes*/
            OnRowCommand="GridView1_RowCommand"
Second, we need create a button in a template field:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="btnClick" runat="server" Text="Click" CommandName="CLICK" CommandArgument='<%# Eval("CustomerID") %>' />
    </ItemTemplate>
</asp:TemplateField>
Please note we set the CommanName to "CLICK" and the CommandArgument to '<%# Eval("CustomerID") %>'. I will explain this soon in the code behind file.

Last, we can now handle the event in the code behind file:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    // Check the command name
    if (e.CommandName == "CLICK")
    {
        // Do some thing here.
    }
}
In most case, you may need the DataKey for the row where the button raised the event. The most simple way is to use the CommandArgument properties. As you've already noticed, we use Eval() to assign the "CustomerID" to CommandArgument. Then in the code, you can retrieve it like this:

        string id = e.CommandArgument.ToString();
Please note, the CommandArgument can be any string but usually we set DataKey to it as DataKey is the link between the row and your DataSet. To go further, you can use your own function to instead the Eval() and bind value which cannot be simply retrieved from the DataSource.

But can we assign the RowIndex instead of DataKey? As Eval() only can bind the value from the DataSource, it seems there is no way to assign the RowIndex to CommandArgument. But we do have an alternative way! We can use the RowDataBound event in the GridView and then bind the RowIndex to CommandArgument.

First, register the event:

<asp:GridView /*all other attributes*/ OnRowDataBound="GridView1_RowDataBound">
Then, assign the RowIndex to CommandArgument:

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Button btn = (Button)(e.Row.FindControl("btnClick"));
                btn.CommandArgument = e.Row.RowIndex.ToString();
            }
        }
Finally, retrieve the RowIndex through e.CommandArgument:

        int rowIndex = int.Parse(e.CommandArgument.ToString());
        GridView gv = (GridView)sender;
        string dataKey = gv.DataKeys[rowIndex].Value.ToString();
Actually, you may have noticed that the DataKey can be retrieved thought the RowIndex. Yes, the DataKeys collection will keep the right sequence when you sort, page the GridView data. Thus you will be guaranteed always get the correct DataKey to the row. So you may consider always pass the RowIndex instead of DataKey.

For those who think using the RowDataBound Event can be tedious, there do have a short cut. You can use the ButonField in the GridView. The CommandArgument will be automatically set as the RowIndex. For example:

                <asp:ButtonField CommandName="CLICK2" Text="Use ButtonField" ButtonType="Button" />
When handling the RowCommand, if e.CommandName == "CLICK2", then e.CommandArgument will have the value of the RowIndex although we don't explicitly assign it. The drawback is you will lose the flexibility of using Template Field.

3. Handling the Event from the Control itself

The above 2 methods have a flaw by nature. Thus they require the control must implement IButtonControl interface to use the CommandName. Somehow you may need to handle the control such as checkbox, dropdonwlist and etc that don't provide you a CommandName property. Or you just want to handle the event in the Button_Click rather than the GridView Events.

First we should know that all the controls in a ASP.Net page are all organized in a hierarchy so we can always go up to the parent control and in the end is the Page. Here we can either use NamingContainer or Parent property to achieve our goal. They are similar but slightly different in hierarchy.

Using NamingContainer property is simpler. The hierarchy here is the GridView contains GridViewRow and the GridViewRow contains the Button which raised the event. Bear this in mind, we have the following code:

            // gets the button that raised the event
            Button btn = (Button)sender;


            // get the row which the button is in.
            GridViewRow row = (GridViewRow)btn.NamingContainer;
            // get the the gridview contains that row.
            GridView gv = (GridView)row.NamingContainer;
            int rowIndex = row.RowIndex;
            string dataKey = gv.DataKeys[rowIndex].Value.ToString();
So we can easily get the RowIndx and DataKey.

Using Parent property is cumbersome as the hierarchy is more complex and contains one type (ChildTable) which is only use by the .Net framework. The hierarchy is GridView->ChildTalbe->GridViewRow-> DataControlFieldCell->Button:

            // gets the button that raised the event
           Button btn = (Button)sender;
// gets the cell
            DataControlFieldCell cell = (DataControlFieldCell)btn.Parent;
            // gets the row
            GridViewRow row = (GridViewRow)cell.Parent;
            // gets the gridview
            // please note the row.Parent will return a ChildTable which is a type supports the .Net framework infrastructure.
            // It's not used by the user so we don't have a type for that.
            GridView gv = (GridView)((row.Parent).Parent);
There is no need to use the Parent property as the NamingContainer property can do the job better. But to know something more is not a bad idea.

By using this third method, you can get the RowIndex and DataKey from any event raised by a control. E.g. you can handle a Checkbox "CheckChange" event (remember you need to set AutoPostBack="True" in the CheckBox properties). A sample codes:

                    <ItemTemplate>
                        <asp:CheckBox runat="server" AutoPostBack="True"
                            oncheckedchanged="cbTest_CheckedChanged" />
                    </ItemTemplate>
        protected void cbTest_CheckedChanged(object sender, EventArgs e)
        {
            // gets the control that raised the event
            CheckBox cb = (CheckBox)sender;


            // get the row which the control is in.
            GridViewRow row = (GridViewRow)cb.NamingContainer;
            // get the the gridview contains that row.
            GridView gv = (GridView)row.NamingContainer;


            int rowIndex = row.RowIndex;
            string dataKey = gv.DataKeys[rowIndex].Value.ToString();


            DisplayIndexAndDatakey(rowIndex.ToString(), dataKey);
        }

Conclusion

I have showed three different ways to get the RowIndex and the DataKey from a Control event inside a GridView. They all have different strength so you need to choose them wisely.


 

 



2010年11月2日星期二

My first blog on blogger

I will try to write down all the thought and learning of programming here. I'm gonna focus on Asp.net and C#.

Also, blogging is a way to improving my writing English.