?
Solved

Adding Event Handlers within datagrid

Posted on 2006-05-22
16
Medium Priority
?
386 Views
Last Modified: 2012-08-13
Hello.

I have a datagrid that will only ever have a single record.
I want to call an event when a checkbox is checked/unchecked that will display extra fields.
I have scoured the forums for a solution to this. I feel sure it must be possible.

I just don't seem to be able to find a way to get a reference to the controls within the datagrid (unless i am using one of the datagrids built in commands - update,delete etc)

I have got this far.

This is the function i am calling from the grid.

    public void showEmailReminderInfo_CheckChanged(object s, DatagridItemEventArgs e)
    {
        Panel pnlEmailReminderInfo = ((Panel)e.Item.FindControl("pnlEmailReminderInfo"));
        CheckBox chkEmailAlert = ((CheckBox)e.Item.FindControl("chkEmailAlert"));

        if (chkEmailAlert.Checked)
            pnlEmailReminderInfo.Visible = false;
        else
            pnlEmailReminderInfo.Visible = true;
    }



This is how I have added the event handler to the datagrid.

    // datagrid item event
    private void datagrid_ItemCreated(object s, DataGridItemEventArgs e)
    {

        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            CheckBox cb = ((CheckBox)e.Item.Cells[0].FindControl("CheckBoxID"));

            cb.CheckedChanged += new EventHandler(this.showEmailReminderInfo_CheckChanged);
        }
    }


I've really no idea if this is correct or not. I seem to have been going backwards and forwards with different methods for an age.

Any help very much appreciated.

Dave

0
Comment
Question by:weerdboil
  • 9
  • 5
  • 2
16 Comments
 
LVL 6

Expert Comment

by:fizch
ID: 16737143
I think that you might be able to put the attribute CommandName as "Edit" then handle the ItemCommand event and watch for an edit. I'm not 100% on that, but I know that I have done something similar. I will continue to try to find my working solution.
0
 
LVL 6

Expert Comment

by:fizch
ID: 16737262
Ok, I'm having a hard time finding it. Another suggestion would be to disable that control, and place a button next to it. Handle the event of that button, change the status of the check box, and do any additional processing.
0
 
LVL 9

Expert Comment

by:HappyFunBall
ID: 16737377
Couple of things to try:

- In the CheckChanged function, you are finding the control "chkEmailAlert", but in the ItemCreated event handler you're grabbing a control called "CheckBoxID" and assigning an event to it.  Make sure you're working with the correct checkbox ID.

- In case that was just a typo when you posted the question, make sure that the AutoPostBack property of the checkbox is set to true.  I believe that's necessary.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:HappyFunBall
ID: 16737435
Also, the logic appears backwards on the CheckChanged function.  If the chkEmailAlert.Checked property is true you'll probably want to make the panel visible.
0
 

Author Comment

by:weerdboil
ID: 16738200
hi guys.

thanks for the replies.

it was a typo - i've been going backwards and forwards like a madman.
i have got autopostback set to true, and it does post back.
i'm absolutely sure this can be done.

the problem seems to be getting hold of a reference to the checkbox. this is because it is within the datagrid. i can get into the showEmailReminderInfo_CheckChanged void no bother but I get...

Object reference not set to an instance of an object.

....when i try to access the checkbox reference.

I've tried page.FindControl() and object.FindControl() and datagrid.findControl() but none of these work either.

Any other ideas.

Thanks very much,
Dave



0
 
LVL 6

Expert Comment

by:fizch
ID: 16738250
You will need to access it as part of the data item. Try just using e.Items.FindControl. It is part of the data item. You could probably just bypass the cell reference all together.
0
 
LVL 6

Expert Comment

by:fizch
ID: 16738269
My next question would be why are you trying to read in data from the form in the ItemCreated event? Isn't that raised when data is bound to the grid?
0
 

Author Comment

by:weerdboil
ID: 16738696
hi.

i'm definitely clutching at straws with the ItemCreated event I know :).

ok. so here is where i'm at:

code behind

    public void showEmailReminderInfo_CheckChanged(object s, DataGridItemEventArgs e)
    {
        Panel pnlEmailAlertDate = (Panel)(e.Item.FindControl("pnlEmailAlertDate"));
        CheckBox chkEmailAlert = (CheckBox)(e.Item.FindControl("chkEmailAlert"));

        if (chkEmailAlert.Checked)
            pnlEmailAlertDate.Visible = true;
        else
            pnlEmailAlertDate.Visible = false;

    }


page

                                <tr>      
                                    <td>email reminder</td>
                                    <td>
                                        <asp:CheckBox runat="server" id="chkEmailAlert" cssClass="inputNoBorder"
                                            OnCheckedChanged="showEmailReminderInfo_CheckChanged" AutoPostBack="true" />
                                        <asp:Label runat="server" ID="lblEmailAlertInfo" /></td>
                                </tr>
                               
                                <asp:Panel ID="pnlEmailReminderInfo" runat="server" Visible="false">
                                <tr>                                                        
                                    <td valign="top">reminder date</td>
                                    <td><asp:Calendar runat="server" id="calEmailAlertDate" SelectedDate='<%# Eval("date_email_alert") %>'
                                                VisibleDate='<%# Eval("date_email_alert") %>'  SelectedDayStyle-BackColor="red" />
                                    </td>
                                </tr>
                                </asp:Panel>


all i want to do is show and hide the panel onCheckChanged, but i cannot seem to pick up the references to the controls.

any ideas?

thanks for your help again.






0
 
LVL 6

Expert Comment

by:fizch
ID: 16741982
Try using the ItemCommand event, and remove the checkbox. Replace it with a button and set the command argument to "Edit".
0
 

Author Comment

by:weerdboil
ID: 16743571
tried that.
same error. no instance reference.

it doesn't appear to be possible to access items that are within the datagrid from a function that doesn't have access to the datagrids eventArgs.

0
 
LVL 6

Expert Comment

by:fizch
ID: 16743627
I've got some code here, similar to what you are trying in that it finds the control on the edited (or in this case inserted) line. Take a look at this, and you should see that you can use the ItemCommand event to access the form fields you are looking for.

    Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
        If e.CommandName = "Insert" Then
            If Not IsValid Then Exit Sub
            Try
                Dim dr As dsDivisionType.irDivisionTypeRow = DsDivisionType1.irDivisionType.NewirDivisionTypeRow

                Dim currentText As TextBox
                currentText = e.Item.FindControl("addId")
                dr.DivisionTypeId = currentText.Text

                currentText = e.Item.FindControl("addDescription")
                dr.Description = currentText.Text

                DsDivisionType1.irDivisionType.AddirDivisionTypeRow(dr)
                SqlDataAdapter1.Update(DsDivisionType1, "irDivisionType")

                DataGrid1.EditItemIndex = -1
                lblMessage.Text = "Record Added"
            Catch ex As Exception
                lblMessage.Text = ex.Message
            End Try

            DataGrid1.ShowFooter = True
            RefreshDatabindings()
        End If
    End Sub
0
 
LVL 6

Expert Comment

by:fizch
ID: 16743656
If you need me to rewrite this in C#, I can definitely help there.
0
 

Author Comment

by:weerdboil
ID: 16744250
ok. i see what you mean.

i'm ok with the c# conversion, but how do i wire up to my itemCommand function in the datagrid?

i have this

           OnItemCommand="showEmailReminderInfo_ItemCommand"

and i have this

          <asp:Button runat="server" id="chkEmailAlert" cssClass="inputNoBorder" CommandName="email"  Text="email options" />
0
 
LVL 6

Accepted Solution

by:
fizch earned 1000 total points
ID: 16744665
I think that where ever you set those events in the designer, it is looking for client-side methods. You should be able to click on the datagrid in the design view, and look at the properties. At the top of the properties window, there is a button for events (it looks like a lightning bolt). Click on that, and then double click on OnItemCommand and that will create the handler for the event. You will do a check similar to the first line of code in my function. Just change insert to "email".
0
 

Author Comment

by:weerdboil
ID: 16751520
hey up mate.

you have been right all along. it was just a case of hooking the button in my datagrid it up to the itemCommand event.

thanks very much indeed for bearing with me.
0
 
LVL 6

Expert Comment

by:fizch
ID: 16751632
Not a problem. I'm glad to have been of assistance.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

750 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question