C# asp.net checkbox not firing when unchecked - c#

I have found this question a few places but no solutions...
I have a checkbox in a gridview:
<asp:TemplateField HeaderText="Closed?">
<ItemTemplate >
<asp:CheckBox ID="Status_CB" runat="server" AutoPostBack="true"
OnCheckedChanged="Status_CB_CheckedChanged"
EnableViewState="true" ViewStateMode="Enabled"
Checked='<%# Convert.ToString(Eval("cStatus")) == "1" ? true : false %>'/>
</ItemTemplate>
</asp:TemplateField>
codebehind:
protected void Page_Load(object sender, EventArgs e) {
if (!int.TryParse(Session["FacilityID"].ToString(), out FId)) {
FId = 0;
}
if (!Page.IsPostBack) {
if (!string.IsNullOrEmpty(Request.QueryString.Get("WorkCenter"))) {
wc = Request.QueryString.Get("WorkCenter");
WorkcenterHeader.InnerText = wc + " Schedule ";
HiddenWorkCenter.Value = c;
}
if (!SQLHasData()) {
SavePrioritiesToSQL();
}
BindGrid();
}
}
protected void Status_CB_CheckedChanged(object sender, EventArgs e) {
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow) cb.Parent.Parent;
}
When i check the box originally, it works. When i uncheck it, the breakpoint i have on the first line of Status_CB_CheckedChanged does not fire at all.
What am i missing any one know?
UPDATE - here is the table, it is nested. i wonder if that is the reason it will not call the postback on uncheck...
UPDATE - ok i gave up, this must be a bug with nested gridview in asp so if you have a nested gridview, i recommend not using checkboxes. I switched mine to a text field of the cStatus "open" or "closed" and use a button with a command argument that is the row index:
<asp:GridView ID="JobInfo_GV" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid2" OnRowCommand="JobInfo_GV_RowCommand">
<asp:BoundField DataField="cStatus" HeaderText="Status" ReadOnly="True" HeaderStyle-CssClass="center-row" ItemStyle-CssClass="center-row"/>
<asp:TemplateField HeaderText="Update">
<ItemTemplate >
<asp:Button id="UpdateClosed" commandname="Select" buttontype="button" Text="ToggleStatus" runat="server" CommandArgument='<%# Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
then the C#:
protected void JobInfo_GV_RowCommand(object sender, GridViewCommandEventArgs e) {
var grid = (GridView)sender;
var errorMessage = string.Empty;
if (grid != null) {
int index = 0;
if (int.TryParse(e.CommandArgument.ToString(), out index) ){
GridViewRow row = grid.Rows[index];

I just created a project and reused your code as part of it.
It works as you expect:
Note you need to set AutoPostBack="true" for the Checkbox control
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GV" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name">
</asp:BoundField>
<asp:TemplateField HeaderText="Closed?">
<ItemTemplate>
<asp:CheckBox ID="Status_CB" runat="server" AutoPostBack="true"
OnCheckedChanged="Status_CB_CheckedChanged"
EnableViewState="true" ViewStateMode="Enabled"
Checked='<%# Convert.ToString(Eval("cStatus")) == "1" ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
And the Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGrid();
}
public class DataS
{
public int cStatus { get; set; }
public string Name { get; set; }
}
private void BindGrid()
{
List<DataS> list = new List<DataS>() { new DataS() { Name = "Name1", cStatus = 1 }, new DataS() { Name = "Name2", cStatus = 1 }, new DataS() { Name = "Name3", cStatus = 0 } };
GV.DataSource = list;
GV.DataBind();
}
protected void Status_CB_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.Parent.Parent;
}
}
}

Related

event handling is not working in my asp.net web forms web application

The update button Onclick event is not working.
I inserted one more button called button1 for testing if it works, but found that it is not working, even Icacked in other web forms in the app
It is not working at all.
Only page load event-driven is working.
Update:
The problem is not solved with other controls. For example, after the user clicks on an update button, a fucntion will be called that checks the value in the textbox and make some calculation.
After debugging, I found that the program cannot read any values from the textbox.
Note: I am using packages like bootstrap, Ajax as they are already built-in in the asp.net web forms web applications. I have also tried to exclude them from the project as mentioned in some references, however, nothing changed.
Here is my code for Shopping Cart web form:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Celebreno.Models;
using Celebreno.Cart;
//to use IOrderedDictionary
using System.Collections.Specialized;
using System.Collections;
using System.Web.ModelBinding;
namespace Celebreno
{
public partial class ShowCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//2- Display the total of cart by calling GetTotal() function(located in Actions_of_Cart class)
//and then store the return value in a new variable, then dispaly it in a label
using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
{
//declare a new variable to store the total into it
decimal cartTotal = 0;
cartTotal = usersShoppingCart.GetTotal();
if (cartTotal > 0)
{
//Display Total in a label that has property " Enable ViewState = False"
// ViewSate used
LblTotal.Text = String.Format("{0:c}", cartTotal);
}
else
{
LblTotalText.Text = "";
LblTotal.Text = "";
//HtmlGenericControl
ShoppingCartTitle.InnerText = "The Shopping Cart is Empty";
//not yet needed
UpdateBtn.Visible = false;
// CheckoutImageBtn.Visible = false;
}
Button1.Click += Button1_Click;
}
}
//1- decalre the "select Method" (used in GridView in Source Code) to return the value of..
//..calling GetCartItems(), which is defined in Actions_of_Cart DB class
public List<ItemsInCart> GetShoppingCartItems()
{
Actions_of_Cart actions = new Actions_of_Cart();
return actions.GetCartItems();
}
//
public List<ItemsInCart> UpdateCartItems()
{
using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
{
//new var
String cartId = usersShoppingCart.GetCartId();
//The UpdateCartItems method gets the updated values for each item in the shopping cart.
//Then, the UpdateCartItems method calls the UpdateShoppingCartDatabase method
//to either add or remove items from the shopping cart.
//Once the database has been updated to reflect the updates to the shopping cart,
//the GridView control is updated on the shopping cart page by calling the DataBind method
//for the GridView. Also, the total order amount on the shopping cart page is updated
//to reflect the updated list of items.
Actions_of_Cart.ShoppingCartUpdates[] cartUpdates = new Actions_of_Cart.ShoppingCartUpdates[CartList.Rows.Count];
for (int i = 0; i < CartList.Rows.Count; i++)
{
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
//ProductId related to struct in Actions
cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ID"]);
CheckBox cbRemove = new CheckBox();
cbRemove = (CheckBox)CartList.Rows[i].FindControl("RemoveItem");
cartUpdates[i].RemoveItem = cbRemove.Checked;
TextBox quantityTextBox = new TextBox();
quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
}
usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
CartList.DataBind();
//dispaly updated total value
LblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
return usersShoppingCart.GetCartItems();
}
}
public static IOrderedDictionary GetValues(GridViewRow row)
{
try
{
IOrderedDictionary values = new OrderedDictionary();
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.Visible)
{
// Extract values from the cell.
cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
}
}
return values;
}
catch (Exception exp)
{
throw new Exception("ERROR1" + exp.Message.ToString(), exp);
}
}
protected void UpdateBtn_Click(object sender, EventArgs e)
{
UpdateCartItems();
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "IT is working ";
}
}
}
Source Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ShowCart.aspx.cs" Inherits="Celebreno.ShowCart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div id="ShoppingCartTitle" runat="server" class="ContentHead"><h1>Shopping Cart</h1></div>
<%--Start of the GridView to display the items in the cart--%>
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
ItemType="Celebreno.Models.ItemsInCart" SelectMethod="GetShoppingCartItems"
CssClass="table table-striped table-bordered" >
<Columns>
<%--problem solved : change "ID" to "ServicePack.ID"--%>
<asp:BoundField DataField="ServicePack.ID" HeaderText="Service Package ID" SortExpression="ID" />
<asp:BoundField DataField="ServicePack.Provider" HeaderText="Provider" />
<asp:BoundField DataField="ServicePack.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}"/>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.ServicePack.UnitPrice)))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove Item">
<ItemTemplate>
<%--checkbox for removing the item--%>
<asp:CheckBox id="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%--End of the GridView--%>
<div>
<p></p>
<strong>
<%--2 (display the total of the cart--%>
<asp:Label ID="LblTotalText" runat="server" Text="Order Total: "></asp:Label>
<asp:Label ID="LblTotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
</div>
<br />
<table>
<tr>
<td>
<%--3 ( add update button) --%>
</td>
<td>
<asp:Button ID="UpdateBtn" runat="server" Text="Button" OnClick="UpdateBtn_Click" />
<asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Test"></asp:Label>
</td>
</tr>
</table>
</asp:Content>
solved : by adding two attributes as shown below
<asp:Button ID="UpdateBtn" runat="server" OnClick="UpdateBtn_Click" Text="Button" CausesValidation="False" UseSubmitBehavior="false" />

Set checkbox as checked in Repeater/CheckboxList

I'm using a Repeater to show some data coming from a web service.
My Repeater structure is:
<asp:Repeater ID="rptgrp" runat="server">
<ItemTemplate>
<asp:CheckBoxList ID="chkBoxListGoup" runat="server"
DataSource='<%# DataBinder.Eval(Container.DataItem, "Titles")%>'
DataTextField="Title"
DataValueField="IDTitle">
</asp:CheckBoxList>
</ItemTemplate>
</asp:Repeater>
Now, my web service returns these fields in "Titles":
1) Title
2) IDTitle
3) isUserTitle
Now, I would like to set checked a checkbox when isUserTitle is = 1.
How can I do that?
You can find checkboxlist as follows
Find checkboxlist in itemdatabound,
check item text of every checkboxlist using loop,
select the item whose text is 1
Protected void Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBoxList chklst = (CheckBoxList)e.Item.FindControl("chkBoxListGoup");
for (int i = 0; i < chk.Items.Count; i++)
{
if (chk.Items[i].Text == "1")
{
chk.Items[i].Selected = true;
}
}
}
}
Try changing <asp:CheckBoxList ID="chkBoxListGoup" runat="server"
to
<asp:CheckBoxList ID="chkBoxListGoup" Checked='<%#Eval("Flag")%>' runat="server"
Flag being your Column..
Then in your method or event handler you want to run some code to say if this value = 1 checked, elseif value = 0 unchecked...
Here is sample code that demonstrates the idea:
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using WebApp.RepeaterCheckboxList.TODODatasetTableAdapters;
namespace WebApp.RepeaterCheckboxList
{
public partial class WebForm1 : System.Web.UI.Page
{
IEnumerable<TODODataset.TasksViewRow> view;
IEnumerable<TODODataset.TasksViewRow> subview;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TasksViewTableAdapter adp = new TasksViewTableAdapter();
var dt = adp.GetData();
view = dt.AsEnumerable();
var names = (from x in view
select new
{
Person = x.Name,
ID = x.PersonID
}).Distinct();
DataList1.DataSource = names;
DataList1.DataBind();
}
}
protected void CheckBoxList1_DataBound(object sender, EventArgs e)
{
CheckBoxList theList = (CheckBoxList)sender;
var person = ((DataListItem)theList.Parent).DataItem as dynamic;
var name = person.Person;
var id = person.ID;
var vw = subview;
for (int i = 0, j = vw.Count(); i < j; i++)
{
var task = vw.ElementAt(i);
theList.Items[i].Selected = task.Completed;
}
}
protected IEnumerable<TODODataset.TasksViewRow> GetTasks(object data)
{
var vw = data as dynamic;
return subview = (from x in view
where x.PersonID == vw.ID
select x);
}
}
}
Aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.RepeaterCheckboxList.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div style="padding:5px">
<h3><%# Eval("Person") %></h3>
<div>
<asp:CheckBoxList OnDataBound="CheckBoxList1_DataBound" ID="CheckBoxList1"
runat="server"
DataTextField="TaskDesc" DataValueField="TaskID"
DataSource="<%# GetTasks(Container.DataItem) %>"></asp:CheckBoxList>
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
If you are interested in the data, click here
Try just setting the Checked value to the object being Evaled.
<asp:Repeater ID="rptgrp" runat="server">
<ItemTemplate>
<asp:CheckBoxList ID="chkBoxListGoup" runat="server"
Checked=<%# Eval("isUserTitle") %>>
</asp:CheckBoxList>
</ItemTemplate>
</asp:Repeater>

Pass client id to code behind

Is there some way to pass the unique client id to codebehind? I have a imagebutton in a gridview and I wish to do something like this:
<asp:ImageButton ID="imbView" runat="server" ToolTip="View details" ImageUrl="~/css/images/View.png" CommandName="wView" CommandArgument='#<%=imbView.ClientID%>' />
On debugging though I see that my CommandArgument is #<%=imbView.ClientID%>..
To specify: I want to pass something that uniquely identifies generated elements (and I thought that the ClientID would be a good way to identify it).
Huh ?
Assuming you have
<asp:ImageButton ID="imbView" runat="server" ToolTip="View details" ImageUrl="~/css/images/View.png" CommandName="wView" OnCommand="aaa" />
then -
protected void aaa(object sender, CommandEventArgs e)
{
var a= (sender as Control).ClientID;
}
Here is how you retrieve CommandArgument inside RowCommand event.
You can also use e.CommandSource as ImageButton inside RowCommand event.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Detail">
<ItemTemplate>
<asp:ImageButton ID="imbView" runat="server"
ToolTip="View details" ImageUrl="~/css/images/View.png"
CommandName="wView"
CommandArgument='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Name" DataField="Name">
</asp:BoundField>
</Columns>
</asp:GridView>
Code Behind
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = new List<Item>
{
new Item {Id = 1, Name = "John"},
new Item {Id = 2, Name = "Eric"},
};
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "wView")
{
var imageButton = e.CommandSource as ImageButton;
string clientId = imageButton.ClientID;
int id = Convert.ToInt32(e.CommandArgument);
}
}

Gridview click on row enable controls

I have a gridview. The gridview has a textbox multiline that keeps an text. After that I have a column with imagebutton named approved, and one named not approved. I want to force the user before click approved or not approved to read the text inside the multiline box. How can I achieve this programmatically? I know I should create a Rowdatabound Event, but what I should do with the code? I am using c# ASP.NET web application.
I know you can track the scroll bar of the browser using javascript but I've personally never come across similar functionality for a text box. I would suggest trying a slightly different approach, why don't you add an extra column to you grid view which has a check box control for - I've read and accepted the agreement. And the Approve button will only be enabledd when the checkbox is checked, here's an example:
ASPX:
<div>
<asp:ScriptManager ID="sm" runat="server" />
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false" OnRowDataBound="grid_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox TextMode="MultiLine" runat="server" ID="txtAgreement" Text='<%# Eval("Agreement") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
I have read and accepted the agreement
<asp:CheckBox ID="chkAgreement" AutoPostBack="true" runat="server" OnCheckedChanged="CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnAccept" runat="server" Text="Accept" OnClick="Accept" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Code behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var items = new List<License> { new License { Agreement = "Agreement 1" }, new License { Agreement = "Agreement 2" } };
grid.DataSource = items;
grid.DataBind();
}
}
protected void Accept(object sender, EventArgs e)
{
}
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
(e.Row.FindControl("btnAccept") as Button).Enabled = false;
}
protected void CheckedChanged(object sender, EventArgs e)
{
var chkAgreement = sender as CheckBox;
Button btnAccept = null;
if (chkAgreement != null)
{
var row = chkAgreement.Parent.Parent as GridViewRow;
btnAccept = row.FindControl("btnAccept") as Button;
if (btnAccept != null)
if (chkAgreement.Checked)
btnAccept.Enabled = true;
else
btnAccept.Enabled = false;
}
}
}
public class License
{
public string Agreement { get; set; }
}

GridView row in edit mode

I posted similar question before, but I still have some problem with it. I use asp.net 4 and c#.
Please help me to understand I need to change the TEXT for the Label uxTest when a user click the EDIT button for a single row.
Any idea? thanks guys once again and sorry if looks like a duplicates question.
<%# Page Language="C#" %>
<%# Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Create a new table.
DataTable taskTable = new DataTable("TaskList");
// Create the columns.
taskTable.Columns.Add("Id", typeof(int));
taskTable.Columns.Add("Description", typeof(string));
taskTable.Columns.Add("IsComplete", typeof(bool) );
//Add data to the new table.
for (int i = 0; i < 20; i++)
{
DataRow tableRow = taskTable.NewRow();
tableRow["Id"] = i;
tableRow["Description"] = "Task " + i.ToString();
tableRow["IsComplete"] = false;
taskTable.Rows.Add(tableRow);
}
//Persist the table in the Session object.
Session["TaskTable"] = taskTable;
//Bind data to the GridView control.
BindData();
}
}
protected void TaskGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
TaskGridView.PageIndex = e.NewPageIndex;
//Bind data to the GridView control.
BindData();
}
protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
protected void TaskGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
TaskGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = TaskGridView.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
TaskGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
private void BindData()
{
TaskGridView.DataSource = Session["TaskTable"];
TaskGridView.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>GridView example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="TaskGridView" runat="server"
AutoGenerateEditButton="True"
AllowPaging="True"
OnRowEditing="TaskGridView_RowEditing"
OnRowCancelingEdit="TaskGridView_RowCancelingEdit"
OnRowUpdating="TaskGridView_RowUpdating"
OnPageIndexChanging="TaskGridView_PageIndexChanging"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:Label ID="uxTest" runat="server" Text="TEST"></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Code solutions:
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit){
Label dl = (Label)e.Row.FindControl("uxLblTest");// Retrive control here
}
Why do you need to change it, your ItemTemplate and EditItemTemplate can have completely different data/controls. Below I'm show 2 different labels (see the ID's) for the Item/Edit templates. You can change anyway you want, but this is the basic approach to have different view/edit modes.
<asp:TemplateField HeaderText="Test Column">
<ItemTemplate>
<asp:Label ID="uxTest" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.TestColumn") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="uxTestEditMode" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.TestColumn") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

Categories