INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

c# consolidate checkbox CheckedChange functions

c# consolidate checkbox CheckedChange functions

(OP)
I have a web page (intranet) with four checkboxes pulling from bit fields in a database, all with AutoPostBack = True. To make this work, I have four functions to update the appropriate filed when the box is either checked or unchecked. It seems to me, however, that I should be able to use one function since they are all the same except for the field name to be updated

CODE

protected void chkSelect_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");

            string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET NoReceiptNeeded=@Status WHERE TransactionID=@ID";
            string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
            using (var con = new SqlConnection(connStrII))
            using (var updateCommand = new SqlCommand(sql, con))
            {
                updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
                updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
                con.Open();
                int updated = updateCommand.ExecuteNonQuery();
            }
        }

        protected void chkSelect_CheckedChanged2(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");

            string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET TaxCollected=@Status WHERE TransactionID=@ID";
            string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
            using (var con = new SqlConnection(connStrII))
            using (var updateCommand = new SqlCommand(sql, con))
            {
                updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
                updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
                con.Open();
                int updated = updateCommand.ExecuteNonQuery();
            }
        }

        protected void chkSelect_CheckedChanged3(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");

            string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET ReceiptReceived=@Status WHERE TransactionID=@ID";
            string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
            using (var con = new SqlConnection(connStrII))
            using (var updateCommand = new SqlCommand(sql, con))
            {
                updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
                updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
                con.Open();
                int updated = updateCommand.ExecuteNonQuery();
            }
        }

        protected void chkSelect_CheckedChanged4(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");

            string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET DoS=@Status WHERE TransactionID=@ID";
            string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
            using (var con = new SqlConnection(connStrII))
            using (var updateCommand = new SqlCommand(sql, con))
            {
                updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
                updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
                con.Open();
                int updated = updateCommand.ExecuteNonQuery();
            }
        } 

and then the aspx

CODE

<asp:TemplateField HeaderText="No Receipt Needed" HeaderStyle-Width="10%">
    <ItemTemplate>
        <asp:Label ID="lblNoReceiptNeeded" runat="server" Text='<%#Eval("NoReceiptNeeded") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:CheckBox ID="ChckBxNoReceiptNeeded" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged"></asp:CheckBox>
    </EditItemTemplate>
    <HeaderStyle Width="10%"></HeaderStyle>
</asp:TemplateField>

<asp:TemplateField HeaderText="Tax Collected" HeaderStyle-Width="10%">
    <ItemTemplate>
        <asp:Label ID="lblTaxCollected" runat="server" Text='<%#Eval("TaxCollected") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:CheckBox ID="ChckBxTaxCollected" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged2"></asp:CheckBox>
    </EditItemTemplate>
    <HeaderStyle Width="10%"></HeaderStyle>
</asp:TemplateField>

<asp:TemplateField HeaderText="Receipt Received" HeaderStyle-Width="10%">
    <ItemTemplate>
        <asp:Label ID="lblReceiptReceived" runat="server" Text='<%#Eval("ReceiptReceived") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:CheckBox ID="ChckBxReceiptReceived" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged3"></asp:CheckBox>
    </EditItemTemplate>
    <HeaderStyle Width="10%"></HeaderStyle>
</asp:TemplateField>

<asp:TemplateField HeaderText="DoS" HeaderStyle-Width="10%">
    <ItemTemplate>
        <asp:Label ID="lblDoS" runat="server" Text='<%#Eval("DoS") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:CheckBox ID="ChckBxDoS" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged4"></asp:CheckBox>
    </EditItemTemplate>
    <HeaderStyle Width="10%"></HeaderStyle>
</asp:TemplateField> 

If I change the ID to match the field name, can I use that to specify which field to update and therefore have only one function to update the checkbox fields? And if so, how would I go about doing that?

Thanks,
Willie

RE: c# consolidate checkbox CheckedChange functions

There are 2 ways that I know of:

In the HTML markup:
(you can also click on the checkbox and go to the Properties tab. Click the events icon "lightning bold" and type it in there)

CODE

<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="anyCheckBoxChanged" />
<br />
<asp:CheckBox ID="CheckBox2" runat="server" OnCheckedChanged="anyCheckBoxChanged" />
<br />
<asp:CheckBox ID="CheckBox3" runat="server" OnCheckedChanged="anyCheckBoxChanged" />
<br />
<asp:CheckBox ID="CheckBox4" runat="server" OnCheckedChanged="anyCheckBoxChanged" /> 
Then create your code.. see below

OR
In the Code Behind:

CODE

protected void Page_Load(object sender, EventArgs e)
    {
        //Define event here by tying name.event += then tab.
        CheckBox1.CheckedChanged += anyCheckBoxChanged;
        CheckBox2.CheckedChanged += anyCheckBoxChanged;
        CheckBox3.CheckedChanged += anyCheckBoxChanged;
        CheckBox4.CheckedChanged += anyCheckBoxChanged;

    }

    void anyCheckBoxChanged(object sender, EventArgs e)
    {
        //Do stuff here
    } 

RE: c# consolidate checkbox CheckedChange functions

(OP)
What I don't get is here:

CODE

void anyCheckBoxChanged(object sender, EventArgs e)
    {
        //Do stuff here
    } 

In the Do Stuff Here area, how would I modify which field it is updating dependent on which checkbox was clicked? I can modify the aspx page to all point to the same function, that is not a problem. What I don't see is how I can get that single function to modify the correct field in the database depending on which checkbox was clicked without having four different functions in the code behind. I am very new to asp.net and I am trying to find my way thru to best coding practices to keep my code clean and readable and at least fairly modular so that things like updates can be driven by what field or what page is requesting the update.

Thanks,
Willie

RE: c# consolidate checkbox CheckedChange functions

something like this maybe

CODE

protected void anyCheckBoxChanged(object sender, EventArgs e)
    {
        //Do stuff here
        string colName = string.Empty;
        string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET ";
        //other vars here...


        if (sender.Equals(this.CheckBox1))
        {
            colName = "NoReceiptNeeded";
        }
        else if (sender.Equals(this.CheckBox2))
        {
            colName = "TaxCollected";
        }
        else if (sender.Equals(this.CheckBox3))
        {
            colName ="ReceiptReceived";
        }
        else 
        {
            colName = "DoS";
        }

        sql += colName + "NoReceiptNeeded=@Status WHERE TransactionID=@ID";

        //rest of SQL code here....

    } 

RE: c# consolidate checkbox CheckedChange functions

(OP)
OK, that makes sense and I think is exactly what I wasn't getting to. Thank you, I will give that a shot and let you know!

wb

RE: c# consolidate checkbox CheckedChange functions

(OP)
I updated my code to

CODE

public void chkSelect_CheckedChanged(object sender, EventArgs e)
        {
            string colName = string.Empty;
            CheckBox chk = (CheckBox)sender;
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");

            if (sender.Equals(this.NoReceiptNeeded))
            {
                colName = "NoReceiptNeeded";
            }
            else if (sender.Equals(this.TaxCollected))
            {
                colName = "TaxCollected";
            }
            else if (sender.Equals(this.ReceiptReceived))
            {
                colName = "ReceiptReceived";
            }
            else if (sender.Equals(this.DoS))
            {
                colName = "DoS";
            }

            
            string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET " + colName + "=@Status WHERE TransactionID=@ID";
            string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
            using (var con = new SqlConnection(connStrII))
            using (var updateCommand = new SqlCommand(sql, con))
            {
                updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
                updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
                con.Open();
                int updated = updateCommand.ExecuteNonQuery();
            }
        } 

and now get this error

CODE

Compiler Error Message: CS1061: 'VISA._Import' does not contain a definition for 'NoReceiptNeeded' and no extension method 'NoReceiptNeeded' accepting a first argument of type 'VISA._Import' could be found (are you missing a using directive or an assembly reference?)

Source Error:

Line 102:            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");
Line 103:
Line 104:            if (sender.Equals(this.NoReceiptNeeded))
Line 105:            {
Line 106:                colName = "NoReceiptNeeded";
 
Source File: e:\kt-webs\JBK\visa\UpdateImport.aspx.cs    Line: 104 

Is there another method I should be using to get the field name of the checked box?

Thanks,
Willie

RE: c# consolidate checkbox CheckedChange functions

Seems that table Visa.Import does not have a column called "NoReceiptNeeded"

you will have to debug and check the value of the sql string to see if it is correct for each possible scenario.

RE: c# consolidate checkbox CheckedChange functions

(OP)
The table is EcompKviews.dbo.VisaTransactionImportII and it does have the field NoReceiptNeeded. VISA._Import is the namespace and class

RE: c# consolidate checkbox CheckedChange functions

OK, my bad. Then it is telling you there is no checkbox by that name on your page.

RE: c# consolidate checkbox CheckedChange functions

I think you need to be using the RowDataBoundEvent. In there you need to check what checkbox was changed and fire the event.
I am not sure exactly how your page is designed and the flow you want to achieve. But I think you want to use the RowDataBound Event

RE: c# consolidate checkbox CheckedChange functions

(OP)
Hmm... This is a snippet of the aspx page

CODE

<asp:TemplateField HeaderText="Tax Collected" HeaderStyle-Width="10%">
    <ItemTemplate>
        <asp:Label ID="lblTaxCollected" runat="server" Text='<%#Eval("TaxCollected") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:CheckBox ID="TaxCollected" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged"></asp:CheckBox>
    </EditItemTemplate>
    <HeaderStyle Width="10%"></HeaderStyle>
</asp:TemplateField>

<asp:TemplateField HeaderText="Receipt Received" HeaderStyle-Width="10%">
    <ItemTemplate>
        <asp:Label ID="lblReceiptReceived" runat="server" Text='<%#Eval("ReceiptReceived") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:CheckBox ID="ReceiptReceived" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged"></asp:CheckBox>
    </EditItemTemplate>
    <HeaderStyle Width="10%"></HeaderStyle>
</asp:TemplateField> 

and then the codebehind

CODE

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    CheckBox chkb = (CheckBox)e.Row.FindControl("NoReceiptNeeded");
                    if (drv[15].ToString() == "True")
                    { chkb.Checked = true; }
                    else { chkb.Checked = false; }
                    CheckBox chkb2 = (CheckBox)e.Row.FindControl("TaxCollected");
                    if (drv[16].ToString() == "True")
                    { chkb2.Checked = true; }
                    else { chkb2.Checked = false; }
                    CheckBox chkb3 = (CheckBox)e.Row.FindControl("ReceiptReceived");
                    if (drv[17].ToString() == "True")
                    { chkb3.Checked = true; }
                    else { chkb3.Checked = false; }
                    CheckBox chkb4 = (CheckBox)e.Row.FindControl("DoS");
                    if (drv[18].ToString() == "True")
                    { chkb4.Checked = true; }
                    else { chkb4.Checked = false; }
                }
            }
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            showgrid();   
        } 
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            showgrid();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            HiddenField lbl = (HiddenField)GridView1.Rows[e.RowIndex].FindControl("TranID");
            TextBox tx1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("Memo");
           string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
           SqlConnection sqlconII = new SqlConnection(connStrII);
           sqlconII.Open();
           string sqlII = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET Memo='" + tx1.Text  + "' WHERE TransactionID=" + lbl.Value;
        SqlCommand cmd = new SqlCommand(sqlII);
           cmd.CommandType = CommandType.Text;
           cmd.Connection = sqlconII;
           cmd.ExecuteNonQuery ();
           GridView1.EditIndex = -1;
           showgrid ();
        }

        public void chkSelect_CheckedChanged(object sender, EventArgs e)
        {
            string colName = string.Empty;
            CheckBox chk = (CheckBox)sender;
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");

            if (sender.Equals(this.NoReceiptNeeded))
            {
                colName = "NoReceiptNeeded";
            }
            else if (sender.Equals(this.TaxCollected))
            {
                colName = "TaxCollected";
            }
            else if (sender.Equals(this.ReceiptReceived))
            {
                colName = "ReceiptReceived";
            }
            else if (sender.Equals(this.DoS))
            {
                colName = "DoS";
            }

            
            string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET " + colName + "=@Status WHERE TransactionID=@ID";
            string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
            using (var con = new SqlConnection(connStrII))
            using (var updateCommand = new SqlCommand(sql, con))
            {
                updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
                updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
                con.Open();
                int updated = updateCommand.ExecuteNonQuery();
            }
        } 

At this point I am fairly lost as to how I can achieve what I am trying to do, which is trying to consolidate down to one function to update all of the checkboxes when they are clicked. I have it working when I use a function for each checkbox, but since the only difference is the field that is being updated I had thought it would be cleaner to just have one function. Another question, should I just stick with four functions (is it unreasonable or bad practice to try to consolidate down to one function?)?

Thanks,
Willie

RE: c# consolidate checkbox CheckedChange functions

You should try to consolidate your code, but if you have trouble, then just do what works for now until you can go back and fix it

I am not sure what your issue is? Are you getting an error, is your code not running?? Have you stepped through your code?

RE: c# consolidate checkbox CheckedChange functions

(OP)
I am getting an error

CODE

Compilation Error 
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS1061: 'VISA._Import' does not contain a definition for 'NoReceiptNeeded' and no extension method 'NoReceiptNeeded' accepting a first argument of type 'VISA._Import' could be found (are you missing a using directive or an assembly reference?)

Source Error:

Line 102:            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");
Line 103:
Line 104:            if (sender.Equals(this.NoReceiptNeeded))
Line 105:            {
Line 106:                colName = "NoReceiptNeeded";

Source File: e:\kt-webs\JBK\visa\UpdateImport.aspx.cs    Line: 104 

Here is the code that has line 104

CODE

public void chkSelect_CheckedChanged(object sender, EventArgs e)
        {
            string colName = string.Empty;
            CheckBox chk = (CheckBox)sender;
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            HiddenField hiddenID = (HiddenField)row.FindControl("TranID");

            if (sender.Equals(this.NoReceiptNeeded)) <-- line 104
            {
                colName = "NoReceiptNeeded";
            }
            else if (sender.Equals(this.TaxCollected))
            {
                colName = "TaxCollected";
            }
            else if (sender.Equals(this.ReceiptReceived))
            {
                colName = "ReceiptReceived";
            }
            else if (sender.Equals(this.DoS))
            {
                colName = "DoS";
            }

            
            string sql = "UPDATE EcompKviews.dbo.VisaTransactionImportII SET " + colName + "=@Status WHERE TransactionID=@ID";
            string connStrII = ConfigurationManager.ConnectionStrings["visa"].ConnectionString;
            using (var con = new SqlConnection(connStrII))
            using (var updateCommand = new SqlCommand(sql, con))
            {
                updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
                updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
                con.Open();
                int updated = updateCommand.ExecuteNonQuery();
            }
        } 

and the aspx page where it is defined

CODE

<asp:TemplateField HeaderText="No Receipt Needed" HeaderStyle-Width="10%">
    <ItemTemplate>
        <asp:Label ID="lblNoReceiptNeeded" runat="server" Text='<%#Eval("NoReceiptNeeded") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:CheckBox ID="NoReceiptNeeded" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged"></asp:CheckBox>
    </EditItemTemplate>
    <HeaderStyle Width="10%"></HeaderStyle>
</asp:TemplateField> 

Earlier in the codebehind I identify the checkboxes successfully

CODE

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    CheckBox chkb = (CheckBox)e.Row.FindControl("NoReceiptNeeded");
                    if (drv[15].ToString() == "True")
                    { chkb.Checked = true; }
                    else { chkb.Checked = false; }
                    CheckBox chkb2 = (CheckBox)e.Row.FindControl("TaxCollected");
                    if (drv[16].ToString() == "True")
                    { chkb2.Checked = true; }
                    else { chkb2.Checked = false; }
                    CheckBox chkb3 = (CheckBox)e.Row.FindControl("ReceiptReceived");
                    if (drv[17].ToString() == "True")
                    { chkb3.Checked = true; }
                    else { chkb3.Checked = false; }
                    CheckBox chkb4 = (CheckBox)e.Row.FindControl("DoS");
                    if (drv[18].ToString() == "True")
                    { chkb4.Checked = true; }
                    else { chkb4.Checked = false; }
                }
            }
        } 

but I am not sure how to use that in this scenario.

Thanks,
Willie

RE: c# consolidate checkbox CheckedChange functions

All the lines with this.<ddlname> will fail because the ddls do not exist on the page directly, the exist in a template in the GridView.
That's why I said you have to use the RowDataBound Event.
In that event, you use FindControl() to get a reference to each ddl, once you do, then you assign it's checkchanged event to chkSelect_CheckedChanged

RE: c# consolidate checkbox CheckedChange functions

(OP)
Still working on this, thank you for the input.

Willie

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close