I have the following template that I am trying to create a CheckBox event to update the database record when the user puts a checkmark on PersonalCall checkbox, the data type is boolean for true or false. Here is my ASP page source.
protected void CheckBox2_CheckedChanged(Object sender, EventArgs e)
{
CheckBox CheckBox2 = (CheckBox)sender;
bool @PersonalCall = CheckBox2.Checked;
if (CheckBox2.Checked)
{
Update to set PersonalCall to True
}
else
{
Update to set PersonalCall to False
}
}
What would be the code to update the PersonalCall checkbox when the user puts a checkmark? The PersonalCall is boolean with true and false value.
the checkbox in grid view is created dynamically. and according to checkmark in checkbox database is updated. but
while finding control during updating dbase, the control is showing to be null. and an error "Object reference not set to an instance of an object." occurs while execution.
Thanks basheerkal I tried but no luck :( .. Instead it got me the following error, I also removed the definition and it got me to another error..
Both DataSource and DataSourceID are defined on 'GridView2'. Remove one definition.
Description:
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Both DataSource and DataSourceID are defined on 'GridView2'. Remove one definition.
Source Error:
Line 19: {
Line 20: GridView2.DataSource = CallManagementDS_Details;
Line 21: GridView2.DataBind(); Line 22: }
Line 23:
It worked, but I have to do some changes now in order to make it work.. Without the Datasource ID it is a mess, plus it takes a while for a checkmark to update the record.
Is it possible to make it work with the Datasource ID? Because I need the (ExtenNumber = @CallingExtension) AND (ExtractDate = @ExtractDate)" and the ExtenNumber is not a pirmarykey plus they are binded throught datasource id that is in the code
CallManagementDS_Details.SelectParameters.Add("CallingExtension", ExtenNumber);
CallManagementDS_Details.SelectParameters.Add("ExtractDate", ExtractDate);
Matt99
Member
3 Points
44 Posts
Need help: CheckBox event to update database record when checked
May 01, 2012 08:20 AM|LINK
Hi,
I have the following template that I am trying to create a CheckBox event to update the database record when the user puts a checkmark on PersonalCall checkbox, the data type is boolean for true or false. Here is my ASP page source.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="AutoNo" DataSourceID="CallManagementDS_Details"
ForeColor="#333333" GridLines="None" AllowPaging="True">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Personal Call" SortExpression="PersonalCall">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server"
Checked='<%# Bind("PersonalCall") %>' Enabled="true" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
The following datasource that I am trying to update the record when checked
<asp:SqlDataSource ID="CallManagementDS_Details" runat="server"
ConnectionString="<%$ ConnectionStrings:ITD_TestingConnectionString %>"
UpdateCommand="UPDATE [Call_Trans_Detail] SET [PersonalCall] = @PersonalCall WHERE [AutoNo] = @AutoNo">
<UpdateParameters>
<asp:Parameter Name="PersonalCall" />
<asp:Parameter Name="AutoNo" />
</UpdateParameters>
---The code---
protected void CheckBox2_CheckedChanged(Object sender, EventArgs e)
{
CheckBox CheckBox2 = (CheckBox)sender;
bool @PersonalCall = CheckBox2.Checked;
if (CheckBox2.Checked)
{
Update to set PersonalCall to True
}
else
{
Update to set PersonalCall to False
}
}
What would be the code to update the PersonalCall checkbox when the user puts a checkmark? The PersonalCall is boolean with true and false value.
I appreciate any help,
Thank you,
Ashley.Jones
Member
210 Points
51 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 09:00 AM|LINK
Hello,
You just need to put the update query. Refer the link below.
http://www.ezzylearning.com/tutorial.aspx?tid=5187857
RoMiKa
Member
2 Points
1 Post
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 09:46 AM|LINK
hello,
I need a help in handling checkbox in grid view.
the checkbox in grid view is created dynamically. and according to checkmark in checkbox database is updated. but
while finding control during updating dbase, the control is showing to be null. and an error "Object reference not set to an instance of an object." occurs while execution.
here is code of creating grid view
public class AddTemplateFieldtoGridView:ITemplate { ListItemType _type; string _colName; int _colNumber; public AddTemplateFieldtoGridView(ListItemType type, string colname,int ColNumber) { _type = type; _colName = colname; _colNumber = ColNumber; } void ITemplate.InstantiateIn(System.Web.UI.Control container) { switch (_type) { case ListItemType.Item: CheckBox chck = new CheckBox(); chck.Checked = true; chck.ID = "chkDay" + (_colNumber-2).ToString(); chck.DataBinding += new EventHandler(chck_DataBinding); container.Controls.Add(chck); break; } } void chck_DataBinding(object sender, EventArgs e) { CheckBox chck = (CheckBox)sender; GridViewRow container = (GridViewRow)chck.NamingContainer; object dataValue = DataBinder.Eval(container.DataItem, _colName); } }for (int i = 0; i < tbl.Columns.Count; i++) { if (i <= 2) { BoundField field = new BoundField(); field.DataField = tbl.Columns[i].ColumnName; field.HeaderText = tbl.Columns[i].ColumnName; grdAttendanceLst.Columns.Add(field); } else { TemplateField tempf = new TemplateField(); tempf.HeaderText = tbl.Columns[i].ColumnName; //chkAttendance = new CheckBox(); //chkAttendance.ID = "chkDay" + (i - 2).ToString(); //chkAttendance.Checked = true; tempf.ItemTemplate = new AddTemplateFieldtoGridView(ListItemType.Item, tbl.Columns[i].ColumnName, i); grdAttendanceLst.Columns.Add(tempf); } if (i == 0) { grdAttendanceLst.Columns[i].ItemStyle.CssClass = "itemSNo"; grdAttendanceLst.Columns[i].HeaderText = "S.No."; } else if (i == 1) grdAttendanceLst.Columns[i].ItemStyle.CssClass = "itemLeft"; else grdAttendanceLst.Columns[i].ItemStyle.CssClass = "itemCentre"; } grdAttendanceLst.DataSource = tbl; grdAttendanceLst.DataBind();Matt99
Member
3 Points
44 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 11:05 AM|LINK
Hi,
I just added the update query but it did not work.
protected void CheckBox2_CheckedChanged(Object sender, EventArgs e)
{
CheckBox CheckBox2 = (CheckBox)sender;
bool @PersonalCall = CheckBox2.Checked;
if (CheckBox2.Checked)
{
string query = "UPDATE [Call_Trans_Detail] SET [PersonalCall] = 1 WHERE [AutoNo] = @AutoNo";
}
else
{
string query = "UPDATE [Call_Trans_Detail] SET [PersonalCall] = 0 WHERE [AutoNo] = @AutoNo";
}
}
Thanks
basheerkal
Star
10672 Points
2426 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 11:12 AM|LINK
See this sample code. It works.
GridVie, Datasource ..in aspx page
<form id="form1" runat="server"> <div> <asp:SqlDataSource ID="CallManagementDS_Details" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>" SelectCommand="SELECT * FROM Call_Trans_Detail" UpdateCommand="UPDATE Call_Trans_Detail SET PersonalCall = @PersonalCall WHERE (AutoNo = @AutoNo)"> <UpdateParameters> <asp:Parameter Name="PersonalCall" /> <asp:Parameter Name="AutoNo" /> </UpdateParameters> </asp:SqlDataSource> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" > <Columns> <asp:BoundField DataField="AutoNo" HeaderText="ID" ReadOnly="True" SortExpression="AutoNo" /> <asp:TemplateField HeaderText="Personal Call" SortExpression="PersonalCall"> <ItemTemplate> <asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("PersonalCall") %>' Enabled="true" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" /> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> </Columns> </asp:GridView> </div> </form>Code Behind
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; public partial class checkboxevent : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { GridView2.DataSource = CallManagementDS_Details; GridView2.DataBind(); } } protected void CheckBox2_CheckedChanged(object sender, EventArgs e) { CheckBox CheckBox2 = (CheckBox)sender; bool checkedvalued = CheckBox2.Checked; GridViewRow gvr = (GridViewRow)(CheckBox2.NamingContainer); string wherekey = gvr.Cells[0].Text; string constr = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString; string qry = "UPDATE Call_Trans_Detail SET PersonalCall = '" + checkedvalued + "' WHERE AutoNo = " + wherekey; SqlConnection conn = new SqlConnection(constr); conn.Open(); SqlCommand cmd = new SqlCommand(qry, conn); cmd.ExecuteNonQuery(); GridView2.DataSource = CallManagementDS_Details; GridView2.DataBind(); } }Try and respond
(Talk less..Work more)
ZeeshanAnsar...
Participant
878 Points
264 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 11:12 AM|LINK
first of all why you are using SqlDataSource instead for sp to update it
accordingly modify the your CheckBox2_CheckedChanged event as
protected void CheckBox2_CheckedChanged(Object sender, EventArgs e) { CheckBox CheckBox2 = (CheckBox)sender; // call the sp to update PersonalCall = CheckBox2.Checked passing the parameter }and secondly what errors come. let me know
Please 'Mark as Answer' if this post helps you.
Matt99
Member
3 Points
44 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 12:19 PM|LINK
Thanks basheerkal I tried but no luck :( .. Instead it got me the following error, I also removed the definition and it got me to another error..
Both DataSource and DataSourceID are defined on 'GridView2'. Remove one definition.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Both DataSource and DataSourceID are defined on 'GridView2'. Remove one definition.
Source Error:
Line 19: { Line 20: GridView2.DataSource = CallManagementDS_Details; Line 21: GridView2.DataBind(); Line 22: } Line 23:Matt99
Member
3 Points
44 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 12:23 PM|LINK
Here is my complete ASP page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Staff Calls</title> </head> <body> <h2>Staff Calls</h2> <p style="text-decoration: underline; color: #000080;">To indicate complete please put a checkmark in the complete field. </p> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="CallsManagementDS" ForeColor="#333333" GridLines="None" DataKeyNames="ExtractDate,CallingExtension" onselectedindexchanged="GridView1_SelectedIndexChanged"> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:BoundField DataField="ExtractDate" HeaderText="Period" SortExpression="ExtractDate" ReadOnly="True" /> <asp:BoundField DataField="CallingExtension" HeaderText="Extension" SortExpression="CallingExtension" > <ItemStyle HorizontalAlign="Center" /> </asp:BoundField> <asp:BoundField DataField="Total_Amount" HeaderText="Total Amount" SortExpression="Total_Amount" DataFormatString="{0:0.00}" /> <asp:TemplateField HeaderText="Complete" SortExpression="StaffStatus"> <ItemTemplate> <asp:CheckBox ID="Checkbox1" runat="server" Checked=' <%# Bind("StaffStatus")%>' Visible="true" /> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField ShowHeader="False"> <ItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" Visible="true" CommandName="Update" Text="Submit"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:CommandField ShowSelectButton="True" SelectText="Details" /> </Columns> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="SteelBlue" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="SteelBlue" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="SteelBlue" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F5F7FB" /> <SortedAscendingHeaderStyle BackColor="#6D95E1" /> <SortedDescendingCellStyle BackColor="#E9EBEF" /> <SortedDescendingHeaderStyle BackColor="#4870BE" /> </asp:GridView> <asp:SqlDataSource ID="CallsManagementDS" runat="server" ConnectionString="<%$ ConnectionStrings:ITD_TestingConnectionString %>" SelectCommand="SELECT Call_Trans_Header.ExtractDate, Call_Trans_Header.ExtenName, Call_Trans_Header.RecordStatus, Call_Trans_Header.Mnth, Call_Trans_Header.Yr, Call_Trans_Header.StaffStatus, vw_Summary.Total_Amount, Call_Trans_Header.CallingExtension FROM Call_Trans_Header INNER JOIN vw_Summary ON Call_Trans_Header.ExtractDate = vw_Summary.ExtractDate AND Call_Trans_Header.CallingExtension = vw_Summary.ExtenNumber INNER JOIN Staff_Extension_Master ON Call_Trans_Header.CallingExtension = Staff_Extension_Master.Ext WHERE (Staff_Extension_Master.USER_ID = @CurrentUser) ORDER BY Call_Trans_Header.Yr,Mnth " UpdateCommand="UPDATE Call_Trans_Header SET StaffStatus = @StaffStatus WHERE (ExtractDate = @ExtractDate) AND (CallingExtension = @CallingExtension)" onselecting="CallsManagementDS_Selecting"> <SelectParameters> <asp:Parameter Name="CurrentUser" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="StaffStatus" /> <asp:Parameter Name="ExtractDate" /> <asp:Parameter Name="CallingExtension" /> </UpdateParameters> </asp:SqlDataSource> <br /> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="AutoNo" DataSourceID="CallManagementDS_Details" ForeColor="#333333" GridLines="None" AllowPaging="True"> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:BoundField DataField="CallDateTime" HeaderText="Date and Time" ReadOnly="True" SortExpression="CallDateTime" /> <asp:BoundField DataField="ExtenNumber" HeaderText="Extension" ReadOnly="True" SortExpression="ExtenNumber" > <ItemStyle HorizontalAlign="Center" /> </asp:BoundField> <asp:BoundField DataField="Duration" HeaderText="Duration" SortExpression="Duration" > <ItemStyle HorizontalAlign="Center" /> </asp:BoundField> <asp:BoundField DataField="CalledNumber" HeaderText="Number" ReadOnly="True" SortExpression="CalledNumber" /> <asp:BoundField DataField="CalledCountry" HeaderText="Country" ReadOnly="True" SortExpression="CalledCountry" /> <asp:BoundField DataField="CallAmount" HeaderText="Amount (KD)" SortExpression="CallAmount" DataFormatString="{0:0.000}" /> <asp:TemplateField HeaderText="Personal Call" SortExpression="PersonalCall"> <ItemTemplate> <asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("PersonalCall") %>' Enabled="true" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" /> </ItemTemplate> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField ShowHeader="False"> <ItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="SteelBlue" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="SteelBlue" Font-Bold="True" ForeColor="White" /> <PagerSettings Mode="NextPrevious" /> <PagerStyle BackColor="SteelBlue" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F5F7FB" /> <SortedAscendingHeaderStyle BackColor="#6D95E1" /> <SortedDescendingCellStyle BackColor="#E9EBEF" /> <SortedDescendingHeaderStyle BackColor="#4870BE" /> </asp:GridView> <br /> </div> <asp:SqlDataSource ID="CallManagementDS_Details" runat="server" ConnectionString="<%$ ConnectionStrings:ITD_TestingConnectionString %>" SelectCommand="SELECT AutoNo, ExtenStaffID, ExtenName, CallingNumber, CallDateTime, CallDuration, CalledNumber, CalledCountry, CallRate, CallAmount, PersonalCallOrig, ChargeToStaffIDOrig, PersonalCall, ChargeToStaffID, CAST(UnitsDuration / 60 AS varchar(5)) + ':' + CAST(UnitsDuration % 60 AS varchar(5)) AS Duration, AmountInSeconds, globalCallID_callId, Dy, Mnth, Yr, ExtractDate, ExtenNumber FROM Call_Trans_Detail WHERE (ExtenNumber = @CallingExtension) AND (ExtractDate = @ExtractDate)" UpdateCommand="UPDATE [Call_Trans_Detail] SET [PersonalCall] = @PersonalCall WHERE [AutoNo] = @AutoNo"> <SelectParameters> <asp:ControlParameter ControlID="GridView1" Name="CallingExtension" PropertyName="SelectedValue" Type="String" /> <asp:ControlParameter ControlID="GridView1" Name="ExtractDate" PropertyName="SelectedValue" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="AutoNo" /> <asp:Parameter Name="PersonalCall" /> </UpdateParameters> </asp:SqlDataSource> </form> </body> </html>//Here is the code page .aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Response.Write (Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1)); if (!Page.IsPostBack) { GridView2.DataSource = CallManagementDS_Details; GridView2.DataBind(); } } protected void CheckBox2_CheckedChanged(Object sender, EventArgs e) { CheckBox CheckBox2 = (CheckBox)sender; bool checkedvalued = CheckBox2.Checked; GridViewRow gvr = (GridViewRow)(CheckBox2.NamingContainer); string wherekey = gvr.Cells[0].Text; string constr = ConfigurationManager.ConnectionStrings["ITD_TestingConnectionString"].ConnectionString; string qry = "UPDATE Call_Trans_Detail SET PersonalCall = '" + checkedvalued + "' WHERE AutoNo = " + wherekey; SqlConnection conn = new SqlConnection(constr); conn.Open(); SqlCommand cmd = new SqlCommand(qry, conn); cmd.ExecuteNonQuery(); GridView2.DataSource = CallManagementDS_Details; GridView2.DataBind(); } protected void CallsManagementDS_Selecting(object sender, SqlDataSourceSelectingEventArgs e) { e.Command.Parameters["@CurrentUser"].Value = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { string ExtenNumber = GridView1.DataKeys[GridView1.SelectedIndex]["CallingExtension"].ToString(); string ExtractDate = GridView1.DataKeys[GridView1.SelectedIndex]["ExtractDate"].ToString(); CallManagementDS_Details.SelectParameters.Clear(); CallManagementDS_Details.SelectParameters.Add("CallingExtension", ExtenNumber); CallManagementDS_Details.SelectParameters.Add("ExtractDate", ExtractDate); GridView2.DataBind(); } }basheerkal
Star
10672 Points
2426 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 02:29 PM|LINK
You didn't check my code fully ... In it no Datasourece ID was set in aspx page....It is working example i posted.
(Talk less..Work more)
Matt99
Member
3 Points
44 Posts
Re: Need help: CheckBox event to update database record when checked
May 01, 2012 03:41 PM|LINK
Sorry, my mistake..
It worked, but I have to do some changes now in order to make it work.. Without the Datasource ID it is a mess, plus it takes a while for a checkmark to update the record.
Is it possible to make it work with the Datasource ID? Because I need the (ExtenNumber = @CallingExtension) AND (ExtractDate = @ExtractDate)" and the ExtenNumber is not a pirmarykey plus they are binded throught datasource id that is in the code CallManagementDS_Details.SelectParameters.Add("CallingExtension", ExtenNumber);
CallManagementDS_Details.SelectParameters.Add("ExtractDate", ExtractDate);
Thank you,