i have a task for Adding control for linkbutton click.
for this i i have created 5 Uploadcontrols with existing 5 controls by giving visible false.
here i am doing for every click one control is showing from server side.
When i click liknbutton everytime postingback..so to restrict this i have added Updatepanel to link button as given below
<asp:UpdatePanel ID="uploadaddmorepic" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:LinkButton ID="lnkaddmorepics" runat="server" Text="Add More Pics"
onclick="lnkaddmorepics_Click"></asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lnkaddmorepics" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
in link button click
protected void lnkaddmorepics_Click(object sender, EventArgs e)
{
int rowCount = 0;
//initialize a session.
rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
//In each button clic save the numbers into the session.
Session["clicks"] = rowCount;
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
if (i == 0)
{
lblupload6.Visible = true;
FileUpload5.Visible = true;
ddlimage5title.Visible = true;
lblforupload6.Visible = true;
}
if (i == 1)
{
lblforuplaod7.Visible = true;
lblforupload6.Visible = true;
ddlimage6title.Visible = true;
FileUpload6.Visible = true;
}
if (i == 2)
{
lblforuplaod8.Visible = true;
lblforuplaod7.Visible = true;
ddlimage7title.Visible = true;
FileUpload7.Visible = true;
}
if (i == 3)
{
lblforuplaod9.Visible = true;
lblforuplaod8.Visible = true;
ddlimage8title.Visible = true;
FileUpload8.Visible = true;
}
if (i == 4)
{
lblforuplaod10.Visible = true;
lblforuplaod9.Visible = true;
ddlimage9title.Visible = true;
FileUpload9.Visible = true;
}
}
getting firing but controls are not showing for every click..plz help me out
Related
I am a greener in asp.net and trying to implement a use case which describes the process of user's choosing and booking a seat in Online Movie Booking System recently.
Now I have created massive seat controls, web user controls which is defined on the basis of the ImageButton, and a 'Submit' button.
These seat controls, seem to work well. The status of seats reflected by the picture within them can change as you clicked them. In the click event of 'Submit' button, I attempt to gather their states with their IDs but those states all are the same as those in the database, which means the status of these controls did not changed.
So, what should I do to get the current status of those controls when I click the 'Submit' button? Any idea would appreciate!
Seat.ascx
public partial class Seat : System.Web.UI.UserControl
{
private string[] Images = { "~/picture/SeatStatus/Default.png", "~/picture/SeatStatus/Chosen.png", "~/picture/SeatStatus/Unavailable.png" };
public string ImageLoc
{
get
{
return this.SeatControl.ImageUrl;
}
set
{
this.SeatControl.ImageUrl = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (ImageLoc == Images[0])
{
ImageLoc = Images[1];//switch to chosen state
}
else if (ImageLoc == Images[1] )
{
ImageLoc = Images[0]; //switch to available state
}
else
{
//Can not be chosen
}
}
}
ChooseSeat.aspx
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Table ID="SeatTable" runat="server">
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div>
<asp:Button ID="Button1" runat="server" text="Submit" OnClick="Unnamed_Click" />
</div>
CreateControl
TableRow Row = new TableRow();
Row.ID = "Row" + RowNum.ToString();
for (int i = 0; i < str.Length; i++)
{
TableCell Cell;
//'0' represent available, '1' means the seat has been choosen , '2' //stands for unavailable
if (str[i] == '0' || str[i] == '1' || str[i] == '2')
{
Cell = new TableCell();
ColNum++;
Cell.ID = "Row" + RowNum.ToString() + "Cell" + ColNum.ToString();
Seat seat = (Seat)LoadControl("~/Seat.ascx");
seat.ID = "Seat" + Cell.ID;
seat.ID = string.Format("{0}", i);
seat.ImageLoc = Images[str[i] - '0'];
Cell.Controls.Add(seat);
Row.Cells.Add(Cell);
}
else if (str[i] == '3')//3 means passageway
{
Cell = new TableCell();
Cell.ID = "Label" + "Row" + RowNum.ToString() + "Cell" + ColNum.ToString();
Label label = new Label();
label.ID = "Ocup" + Cell.ID;
Cell.Controls.Add(label);
Row.Cells.Add(Cell);
}
else if (str[i] == '-')//'-' means next row
{
SeatTable.Rows.Add(Row);
Row = new TableRow();
RowNum++;
Row.ID = "Row" + RowNum.ToString();
}
else
{
SeatTable.Rows.Add(Row);
break;
}
}
I have a problem with PagedDataSource and UpdatePanel.When I use AsyncPostBackTrigger in my buttons, paging in my page disappear.
Here's asp code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="DataListGallery" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" OnItemDataBound="DataListGallery_ItemDataBound" >
<ItemTemplate>
<asp:HiddenField ID="FieldPhoneId" Value='<%# Eval("Phone_InfoID") %>' runat="server" />
<asp:ImageButton ID="btnShop" OnClick="btnShop_Click" ImageUrl="images/cart.gif" CssClass="left_bt_item" title="header=[خريد] body=[ ] fade=[on]" runat="server" />
<asp:ImageButton CssClass="left_bt_item" title="header=[مورد علاقه] body=[ ] fade=[on]" OnClick="btnFavourite_Click" ID="btnFavourite" ImageUrl="images/unfav.png" runat="server" />
.
.
.
Here's C# code(load event):
protected void Page_Load(object sender, EventArgs e)
{
//http://www.aspdotnetfaq.com/Faq/how-to-determine-whether-an-asynchronous-partial-postback-has-occurred-on-page.aspx
// get a reference to ScriptManager and check if we have a partial postback
if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
{
// partial (asynchronous) postback occured
// insert Ajax custom logic here
}
// enable property is re-creating page controls
else if (!Page.IsPostBack || enable)
{
//enable = false;
if (Page.Request["Page"] != null || Page.Request["Page"] != "")
{
.
.
.
And a button with AsyncPostBackTrigger:
protected void btnFavourite_Click(object sender, ImageClickEventArgs e)
{
// Access to real ImageButton from repeater
ImageButton ib = (ImageButton)sender;
HiddenField hf = (HiddenField)ib.Parent.FindControl("FieldPhoneId");
Favourite objFav = new Favourite(Convert.ToInt32(hf.Value));
Guid userId = objFav.GetUserIdFromUserName(User.Identity.Name);
using (var context = new MobileGalleryEntities())
{
try
{
// Delete favorited
if (objFav.HadFavorited(User.Identity.Name))
{
int phoneInfoId = Convert.ToInt32(Convert.ToInt32(hf.Value));
// Remove favourite
objFav.RemoveFromFavourite(userId);
// Change image
ib.ImageUrl = "~/images/unfav.png";
}
// Add favorite
else
{
// Add phone
objFav.AddToFavourite(userId);
// Change image
ib.ImageUrl = "~/images/favs.gif";
}
}
catch (Exception ex)
{
}
}
}
Here's DataBound event:
protected void DataListGallery_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (User.Identity.IsAuthenticated)
{
try
{
// Get LoginView for access to ImageButton on it.
var loginView = e.Item.FindControl("LoginView1");
ImageButton btnCom = (ImageButton)e.Item.FindControl("btnCompare");
//ImageButton btnFav = (ImageButton)loginView.FindControl("btnFavourite");
ImageButton btnFav = (ImageButton)e.Item.FindControl("btnFavourite");
btnFav.Visible = true;
ImageButton btnShop = (ImageButton)e.Item.FindControl("btnShop");
btnShop.Visible = true;
//HiddenField hf = (HiddenField)loginView.FindControl("FieldPhoneId");
HiddenField hf = (HiddenField)e.Item.FindControl("FieldPhoneId");
List<int> listFav = (List<int>)Session["Fav"];
if (listFav.Contains(int.Parse(hf.Value)))
btnFav.ImageUrl = "~/images/favs.gif";
}
catch(Exception ex)
{
}
}
else
{
ImageButton btnFav = (ImageButton)e.Item.FindControl("btnFavourite");
btnFav.Visible = false;
ImageButton btnShop = (ImageButton)e.Item.FindControl("btnShop");
btnShop.Visible = false;
}
}
When I fire btnFavourite button, paging in my page disapear. but when i use FullPostBack it's work.
Notice that when I use FullPostBack, I re-create controls such as paging control and other control but when I use AsyncPostBackTrigger I didn't re-create controls.
What am I doing?
Thanks.
I have to re-create controls again the same as FullPostBack.
I'm trying to get an aspx datagrid control to perform a post that results in a partial postback (asynchronous) rather than a full postback. I've added scriptmanager, an update panel, and a content template wrapper and yet it still refreshes the page when i select a data item and click add.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True" ></asp:ScriptManager>
<asp:UpdatePanel ID="upPnlLookup" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:DataGrid ID="ObjectPropertiesDataGrid" CellPadding="5" CellSpacing="5" OnItemCommand="ObjectPropertiesDataGrid_ItemCommand" OnItemDataBound="ObjectPropertiesDataGrid_ItemDataBound" AutoGenerateColumns="False" CssClass="List" DataKeyField="id" runat="server">
<asp:TemplateColumn>
<ItemTemplate>
<asp:Panel ID="multiValuePanel" Visible="false" runat="server">
<table>
<tr>
<td valign="top">
<asp:Button ID="addButton" CssClass="button" CommandName="AddValue" Width="65px" Text="Add" runat="server"></asp:Button>
<asp:Button ID="addAllButton" CssClass="button" CommandName="AddAllValue" Width="85px" Text="Add All" runat="server"></asp:Button>
<br />
<asp:ListBox ID="listBoxValues" Width="250px" CssClass="listbox" SelectionMode="Multiple" runat="server"></asp:ListBox>
</td>
<td valign="top">
<asp:Button ID="removeButton" CssClass="button" Text="Remove" Width="65px" CommandName="RemoveValue" runat="server"></asp:Button>
<asp:Button ID="removeAllButton" CssClass="button" Text="Remove All" Width="85px" CommandName="RemoveAllValue" runat="server"></asp:Button>
<br />
<asp:ListBox ID="listBoxCurrentValues" Width="250px" CssClass="listbox" SelectionMode="Multiple" runat="server"></asp:ListBox>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateColumn>
</asp:DataGrid>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="addButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="removeButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="addAllButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="removeAllButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind (snippets/relevant methods):
protected void Page_Load(object sender, EventArgs e)
{
SaveButton.Click += SaveButton_Click;
btnAddChild.Click += btnAddChild_Click;
btnAddChildTop.Click += btnAddChildTop_Click;
DeleteButton.Click += DeleteButton_Click;
CancelButton.Click += CancelButton_Click;
CopyButton.Click += CopyButton_Click;
NewButton.Click += NewButton_Click;
AddSiteButton.Click += AddSiteButton_Click;
RemoveSiteButton.Click += RemoveSiteButton_Click;
ActivateAll.Click += ActivateAll_Click;
DeactivateAll.Click += DeactivateAll_Click;
startDateCalender.SelectionChanged += startDateCalender_SelectionChanged;
endDateCalender.SelectionChanged += endDateCalender_SelectionChanged;
startDateCalender.Load += startDateCalender_Load;
endDateCalender.Load += endDateCalender_Load;
CacheButton.Click += CacheButton_Click;
if (IsPostBack)
return;
if (String.IsNullOrEmpty(Request["id"]))
{
Response.Redirect("default.aspx");
}
else
{
LoadData();
}
}
private void LoadData()
{
Properties = ContentProviderFactory.GetContentProvider().GetObjectTypeProperties(CurrentContentObject.Type, false);
uploadImage.DataSource = DataHelper.GetObjecTypeImageSizes(CurrentContentObject.Type);
uploadImage.Container = CurrentContentObject;
foreach (var property in from Property p in Properties
let objectProperty = CurrentContentObject.GetProperty(p.Id)
where objectProperty == null
select p)
{
CurrentContentObject.Items.Add(property);
}
ObjectPropertiesDataGrid.DataSource = Properties;
var children = ContentProviderFactory.GetContentProvider().GetContentObjectChildren(CurrentContentObject.Id);
dgObjectChildren.DataSource = children.Where(c => c.Active);
dgObjectInactiveChildren.DataSource = children.Where(c => !c.Active);
dgObjectParents.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectParents(CurrentContentObject);
ddlContentTypes.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);
ddlContentTypesTop.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);
SitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSitesAvailable(CurrentContentObject.Id);
SetSitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSites(CurrentContentObject.Id);
if (CurrentContentObject.Id == 0)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "/admin/Contentobjects/ObjectNotFound.aspx");
Response.End();
}
const string DATE_FORMAT = "MM/dd/yyyy";
if (CurrentContentObject.StartDate.ToString(DATE_FORMAT) != SqlDateTime.MinValue.Value.ToString(DATE_FORMAT))
{
startDateTextBox.Text = CurrentContentObject.StartDate.ToShortDateString();
}
if (CurrentContentObject.EndDate.ToString(DATE_FORMAT) != SqlDateTime.MaxValue.Value.ToString(DATE_FORMAT))
{
endDateTextBox.Text = CurrentContentObject.EndDate.Date.ToShortDateString();
}
DataBind();
//if its an orphan child/child, remove 'add child' button and pulldown
if (ddlContentTypes.Items.Count == 0)
{
btnAddChild.Visible = false;
ddlContentTypes.Visible = false;
}
if (ddlContentTypesTop.Items.Count == 0)
{
ddlContentTypesTop.Visible = false;
btnAddChildTop.Visible = false;
}
// Add delete confirmation javascript
DeleteButton.Attributes["onclick"] = "return confirm_object_delete();";
RenderTypeHeader();
RenderBreadcrumb();
if (CurrentContentObject.ParentId == 0)
{
UserInfo.AddToHistory(CurrentContentObject.Id, CurrentContentObject.Name);
}
else
{
UserInfo.AddToHistory(CurrentContentObject.Parent.Id, CurrentContentObject.Parent.Name);
}
startCalenderPanel.Visible = false;
endCalenderPanel.Visible = false;
}
protected void ObjectPropertiesDataGrid_ItemCommand(object sender, DataGridCommandEventArgs e)
{
var id = (int)ObjectPropertiesDataGrid.DataKeys[e.Item.ItemIndex];
switch (e.CommandName.ToLower())
{
case "clearimage":
{
// Delete the image (does not physically remove the image but will be replaced if new a new one updates)
var imageProperty = e.Item.FindControl("imageProperty") as Image;
var tbFileName = e.Item.FindControl("tbFileName") as TextBox;
tbFileName.Text = string.Empty;
imageProperty.ImageUrl = string.Empty;
break;
}
case "addvalue":
{
// Adds a property value to the list of properites
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
foreach(var item in listBoxValues.Items.Cast<ListItem>().Where(item => item.Selected))
{
// Add item to the set values
listBoxCurrentValues.Items.Add(item);
}
for (var i = listBoxValues.Items.Count - 1; i >= 0; i--)
{
if (listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
{
listBoxValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxCurrentValues);
break;
}
case "removevalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
for(var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
{
if(listBoxCurrentValues.Items[i].Selected)
{
listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
listBoxCurrentValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxValues);
break;
}
case "addallvalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
foreach(ListItem item in listBoxValues.Items)
{
// Add item to the set values
listBoxCurrentValues.Items.Add(item);
}
for(var i = listBoxValues.Items.Count - 1; i >= 0; i--)
{
if(listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
{
listBoxValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxCurrentValues);
break;
}
case "removeallvalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
for (var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
{
listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
listBoxCurrentValues.Items.RemoveAt(i);
}
SortListBox(listBoxValues);
break;
}
case "addalldatalistvalue":
{
var dataListValues = e.Item.FindControl("DataListValues") as DataList;
var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;
foreach (DataListItem item in dataListValues.Items)
{
ImageLink imageLink = ImageLinks[id][item.ItemIndex];
CurrentImageLinks[id].Add(imageLink);
}
for (var i = dataListValues.Items.Count - 1; i >= 0; i--)
{
if (CurrentImageLinks[id].Contains(ImageLinks[id][i]))
{
ImageLinks[id].RemoveAt(i);
}
}
dataListValues.DataSource = ImageLinks[id];
dataListCurrentValues.DataSource = CurrentImageLinks[id];
dataListValues.DataBind();
dataListCurrentValues.DataBind();
break;
}
case "removealldatalistvalue":
{
var dataListValues = e.Item.FindControl("DataListValues") as DataList;
var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;
for (var i = dataListCurrentValues.Items.Count - 1; i >= 0; i--)
{
ImageLinks[id].Add(CurrentImageLinks[id][i]);
CurrentImageLinks[id].RemoveAt(i);
}
dataListValues.DataSource = ImageLinks[id];
dataListCurrentValues.DataSource = CurrentImageLinks[id];
dataListValues.DataBind();
dataListCurrentValues.DataBind();
break;
}
}
}
I think you have a runtime error in Page_Load. for example if you have this wrong codes, your page will refresh instead of update:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Response.Redirect("WebForm1.aspx");
int.Parse("");
}
}
also try this :
Control me = FindControl(Request.Params.Get("__EVENTTARGET"));
if(FindControl(me!=addButton && me!=removeButton && me!=addAllButton && me!=removeAllButton)
{
if (IsPostBack)
return;
if (String.IsNullOrEmpty(Request["id"]))
{
Response.Redirect("default.aspx");
}
else
{
LoadData();
}
}
I am trying to add a required field validator to my page at runtime.
Nothing fancy there:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:ValidationSummary ID="ValidationSummary1"
runat="server" ShowMessageBox="True" ShowSummary="False" />
</form>
and # codebehind
protected void Page_Init(object sender, EventArgs e)
{
RequiredFieldValidator theValid = new RequiredFieldValidator();
theValid.ID = "0000" + "RFV";
theValid.ControlToValidate = TextBox1.ID;
theValid.ErrorMessage = "Message here"
theValid.Text = "*";
theValid.Display = ValidatorDisplay.Dynamic;
theValid.EnableClientScript = true;
theValid.EnableViewState = true;
theValid.SetFocusOnError = true;
theValid.Enabled = true;
theValid.Visible = true;
Page.Validators.Add(theValid);
form1.Controls.Add(theValid);
}
When I click the button it only validates server-side, but not client-side. What am I missing?
TIA.
You can to check your code with jquery.
function TextBoxValidate() {
$('input:[type="text"]:[id*="TextBox1"]').each(function () { var txtId = this.id; $('span').each(function () { if (this.controltovalidate == txtId) ValidatorValidate(this); }); });
}
function InitValidationOnClick()
{
$('input:[id*="Button1"]').each(function(){$(this).on('click', function(){TextBoxValidate(); return Page_IsValid;});});
// or other case
//$('form:[id*="form1"]').each(function(){$(this).on('submit', function(){TextBoxValidate(); return Page_IsValid;});});
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitValidationOnClick);
If validator exists in page it will validate on click (submit) event client-side.
Hello All Try This one For Radio Buttons Along With RequiredField Validator
Code
TableRow trow4 = new TableRow();
trow4.Style.Add("width", "100px");
TableCell tcel4 = new TableCell();
Label lb4 = new Label();
lb4.Text = Resources.QcLabelName.Gender;
tcel4.Controls.Add(lb4);
CSSCell(tcel4);
table.Rows.Add(trow4);
RadioButtonList rblist = new RadioButtonList();
rblist.ID = "rbtnmalendfemale";
rblist.Items.Add("Male");
rblist.Items.Add("Female");
tcel4.Controls.Add(rblist);
trow4.Cells.Add(tcel4);
table.Rows.Add(trow4);
rblist.Visible = true;
RequiredFieldValidator rFV5 = new RequiredFieldValidator();
TableCell tcl46 = new TableCell();
rFV5.ControlToValidate = "rbtnmalendfemale";
rFV5.ErrorMessage = "Gendor Selection Is Mandatory";
rFV5.Style.Add("color", "Red");
rFV5.ID = "Reqfield9";
tcl46.Controls.Add(rFV5);
trow4.Cells.Add(tcl46);
table.Rows.Add(trow4);
rFV5.Visible = true;******
i have a below gridview control with a checkbox on it, so my question is when i hit on save button i able to find the checkbox which have been checked and till here no problem, but the problem started when the user tries to uncheck the checkedbox so how would i track the changes and save it into the db that has been checked. anyhelp?
List<Employee> result = new List<Employee>();
long Id = (long)Session["Id"];
result = Employee.GetEmployeeById(Id);
foreach (GridViewRow row in gv.Rows)
{
CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
if (c != null)
{
if (result.Count > 0)
{
foreach (Employee item in result)
{
Label Id = row.FindControl("lblId") as Label;
if (Id.Text == item.Id.ToString())
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<script language="javascript" type="text/javascript">
function SelectAll(cb)
{
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(cb).checked;
}
}
}
}
}
//--------------------------------------------------------------------------------------------.
function Select(cb)
{
var total = parseInt('<%= this.gv.Rows.Count %>');
var counter=0;
var cbSelectAll=document.getElementById(cb);
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
if(cell.childNodes[j].checked)
counter++;
else
counter--;
}
}
}
}
if(counter==total)
cbSelectAll.checked=true;
else if(counter<total)
cbSelectAll.checked=false;
}
</script>
//----------------------------------------------------------------------------------------
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox cbSelect = (CheckBox)e.Row.Cells[0].FindControl("cbSelect");
CheckBox cbSelectAll = (CheckBox)this.gv.HeaderRow.FindControl("cbSelectAll");
cbSelect.Attributes.Add("onclick", "javascript:Select('" + cbSelectAll.ClientID + "')");
cbSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + cbSelectAll.ClientID + "')");
}
}
Yes, store the original value in a hidden field. If always starting with false, you could use JavaScript to set the hidden value to true when the user clicked the checkbox. Using JQuery, you could do:
<asp:TemplateField HeaderText="Select" ItemStyle-CssClass="Checked">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
<asp:HiddenField iD="dh" runat="server" />
</ItemTemplate>
</asp:TemplateField>
$("#<%= Grid.ClientID %>").find(".Checked > :checkbox").each(function() {
$(this).siblings("input[type='hidden']").attr("value", "True");
});
Something like that. On Server side, parse the value and if true, then you know it changed.
HTH.
It may not be the brightest idea, but you can query the database for the current state, and the compare with what you have got from the web page during a postback button click, or something like that. Or you can go with Brians answer.
It is possible to persist a list of objects into the Viewstate and access it in a consequent postback. The only thing is that the object you are trying to persist must be defined as serializable.
Update:
The ViewState approach
I feel this may be suitable for your need, and it requires a bit of linq. You'd need to create a class as follows:
[Serializable()]
public class OptionState
{
//the id of the item
int ID {get;set;}
//state of the checkbox
bool Checked {get;set;}
}
Note the Serializable attribute. This is required for the instance to persist to the viewstate.
Add the list of options to the viewstate:
var lstOptions = (from x in <your_option_store>
select new OptionState{ID = x.ID, Checked = x.Checked}).ToList();
ViewState.Add("options", lstOptions);
Here is a bit of code that should go into your button click:
foreach(GridViewRow row in gvOptions.Rows)
{
//not writing the bit of code
//which gets the ID and the
//state of checkbox of
//the gridview row being processed
OptionState currentState = GetOptionStateObjectFromRow(row);
List<OptionState> lstStates = (List<OptionState>) ViewState["options"];
OptionState originalState = lstStates.FirstOrDefault(x => x.ID == currentState.ID);
if(currentState.Checked != originalState.Checked)
{
//the appropriate db call needs to be done here.
}
}