The problem I'm having is the RowCommand of my GridView will not fire. I've read through millions of posts, and as a result I think I'm even more confused. So, if you can see what specifically it is I've done wrong here, please point it out.
I did ask a similar question a couple of weeks ago, but I was using a gridview nested in a datalist and using 'Include' Siblings of the EntityDataSource to display the Siblings, which are the many side of the relationship to Referral, it's fine for display, but figuring out Edit Update and Delete was nightmareish. So I've tied to simplify it, but am now stopped in my tracks because I'm losing controls somewhere in the postbacks.
I have a master page with a ContentPlaceholder:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.Master.cs" Inherits="HomelessStudent.Web.SiteMasterPage" ViewStateMode="Inherit" EnableViewState="True" %>
<asp:ContentPlaceHolder ID="ContentPlaceHolderAgent" runat="server">
</asp:ContentPlaceHolder>
On the Agent page-
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolderAgent" runat="server">
<asp:Panel ID="SiblingPanel" runat="server" ViewStateMode="Enabled" Visible="True">
<asp:GridView ID="SiblingGridView" runat="server" CssClass="grid"
AutoGenerateColumns="false"
DataKeyNames="Id"
ShowFooter="true"
OnDataBound="SiblingGridView_DataBound"
OnRowEditing="SiblingGridView_RowEditing"
OnRowUpdating="SiblingGridView_RowUpdating"
OnRowCommand="SiblingGridView_RowCommand"
OnRowDeleting="SiblingGridView_RowDeleting" ViewStateMode="Enabled" ClientIDMode="Static">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="SiblingName">
<EditItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("SiblingName") %>' ID="TextBox1"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("SiblingName") %>' ID="Label1"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="NewSiblingName" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="false">
<EditItemTemplate>
<asp:LinkButton runat="server" Text="Update" CommandName="Update" ID="UpdateLinkButton" ></asp:LinkButton> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="False" ID="LinkButton2"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" ID="EditLinkButton" ClientIDMode="Static"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton runat="server" CommandName="AddNew" Text="Add" ID="AddNewLinkButton"></asp:LinkButton> </FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowHeader="True" HeaderText="Delete"></asp:CommandField>
</Columns>
</asp:GridView>
</asp:Panel>
Code behind (binding data here because show only those siblings that belong to a specific record, ID (Guid) for that record is in the queryString, maybe...
if (IsPostBack == false)
{
if (Request.QueryString["id"] == null)
{
if (Session["studentid"] == null)
{
Response.Redirect("StudentPage.aspx");
}
else
{
referral = GetMostRecentReferral((String)Session["studentid"]);
PopulateUI(referral);
}
}
else
{
referral = GetThisReferral(Request.QueryString["id"]);
PopulateUI(referral);
}
}
Then, in PopulateUI(referral)
some stuff...
FillSiblingGrid();
String studentId = ((referral.StudentID).ToString()).Trim();
getSelectedStudentDeatails(studentId);
Session["referralid"] = (Guid)referral.Id;
And fill siblings grid-
private void FillSiblingGrid()
{
if (referral != null)
{
List<Sibling> siblings = new List<Sibling>();
using (HomelessStudentDataEntities db = new HomelessStudentDataEntities())
{
siblings = (from s in db.Siblings
where s.ReferralID == referral.Id
select s).ToList();
}
if (siblings.Count > 0)
{
SiblingGridView.DataSource = siblings;
SiblingGridView.DataBind();
}
else
{
int TotalColumns = SiblingGridView.Rows[0].Cells.Count;
SiblingGridView.Rows[0].Cells.Clear();
SiblingGridView.Rows[0].Cells.Add(new TableCell());
SiblingGridView.Rows[0].Cells[0].ColumnSpan = TotalColumns;
SiblingGridView.Rows[0].Cells[0].Text = "No siblings found";
}
}
}
I faced the similar problem. Enabling the grid view state resolved the problem
Related
I got a gridview where checkboxes are displayed for each and every row. Upon clicking the checkbox the alternate names label should change to textbox with the content in it remaining as it is.
If the user unchecks the checkbox the textbox should again revert back to label.
How can I achieve this in Jquery.
The code behind code is as follows:
<asp:GridView ID="GridView1" runat="server" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" OnClick="checkboxing()" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City Name Id">
<ItemTemplate>
<asp:Label ID="NameId" runat="server" Text='<%# Eval("Name_Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="CityName" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Geo Name">
<ItemTemplate>
<asp:Label ID="GeoName" runat="server" Text='<%# Eval("geoname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ascii Name">
<ItemTemplate>
<asp:Label ID="AsciiName" runat="server" Text='<%# Eval("asciiname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Alternate Names" SortExpression="AlternateNames">
<EditItemTemplate>
<asp:Label ID="AlternateNames" runat="server" Text='<%# Eval("alternateNames") %>'>
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="AlternateNames" runat="server" Text='<%# Eval("alternateNames") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Longitude">
<ItemTemplate>
<asp:Label ID="Longitude" runat="server" Text='<%# Eval("longitude") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Latitude">
<ItemTemplate>
<asp:Label ID="Latitude" runat="server" Text='<%# Eval("latitude") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The Javascript that executes on checking/unchecking the checkbox is the following one:
function checkboxing() {
alert("im here in checkboxing");
$("input:checkbox").click(function () {
if ($(this).is(":checked")) {
alert("This is so true ");
}
else {
alert("false");
}
});
}
Now my intention is
To change the alternate names - Label to Textbox with contents in it remaining as it is for the user to edit,
If the user unchecks the checkbox later, the contents should revert with textbox again changing to Label.
How can achieve this using JQuery
there are two ways to achieve it
1 dynamically create elements on each checkbox click
2 create both label and textbox but hide them on the basis of checkbox event
since you are using strongly typed views the second one should be the better option
if you use the client side input elements you could have dynamically append the element on the basis of click function.
now i would recommend the 2nd method instead of the 1st one because the 2nd one will manipulate the dom which in your case is not a necessity where as the 2nd option will only add a hidden class to your element which is less complex and also a better in terms of performance
The name should be input instead of label, use class each row item instead of id.
Suggestion : from input:checked find the parent row and find name
Demo
you can change the DOM from label to input field
Upon toggling the checkbox, you can enable/disable.
You can also set custom styles to the disabled input field like as if its a label.
Hope the idea is of any help
Try Below. I am assuming you are trying to edit the last row and you have only one checkbox each row.
$(document).ready(function () {
$("table input[type=checkbox]").on("change", function (event) {
var obj = $(event.target);
var tr = $(obj).closest("tr");
var td = $(tr).find("td:last");
if ($(obj).is(":checked")) {
var data = $(td).find("span").html();
$(td).html("<input id=none value=" + data + " />");
}
else {
var data = $(td).find("input").val();
$(td).html("<span >"+data+"</span>" );
}
});
});
Try the below codes
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function toggleControl(chk)
{
var cell = $(chk).parent();
var lbl = $(cell).siblings().find('#lblNames');
var txtbx = $(cell).siblings().find('#txtNames');
var str;
if($(chk).is(':checked'))
{
str = $(lbl).text();
$(lbl).hide();
$(txtbx).val(str);
$(txtbx).show();
}
else {
$(lbl).show();
$(txtbx).hide();
}
}
</script>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" OnClick="toggleControl(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Alternate Names">
<ItemTemplate>
<asp:Label ID="lblNames" ClientIDMode="Static" runat="server" Text='Hello World!'>
</asp:Label>
<input type="text" id="txtNames" style="display:none;" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs file codes:
namespace aspnetWeb
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Student> list = new List<Student>();
for(int i=1;i<=10;i++)
list.Add(new Student { ID = 1, Count = 20 });
GridView1.DataSource = list.AsQueryable();
GridView1.DataBind();
}
}
public class Student
{
public int ID { get; set; }
public int Count { get; set; }
}
}
Want to be able to set an "Edit" linkbutton to visible=false unless the user has a role of "Editor".
Been poking around stackoverflow and elsewhere and so far have not been able to get this to work.
Gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Questions Awaiting Review" AllowSorting="True" PagerSettings-Mode="NumericFirstLast"
OnPageIndexChanging="GridView1_PageIndexChanging" CaptionAlign="Top" EmptyDataText="No Questions Pending Review."
PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large" DataKeyNames="QuestionID"
OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc"
OnPreRender="GridView1_OnPreRender">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="60" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="viewQuestion">View Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Have changed the code behind to use OnPreRender for the gridview, which if the value is hardcoded hides the column. However when I try to retrieve the is in role of editor then the value does not seem to be evaluating correctly. Always returns false even when the user has a role of Editor.
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
if (Roles.IsUserInRole("Editor"))
{
// Enter correct column index.
GridView1.Columns[4].Visible = true;
}
else
{
GridView1.Columns[4].Visible = false;
}
}
Hoping I'm missing something simple, new to asp.net so not unlikely.
Hide last column.
this.GridView1.Columns[this.GridView1.Columns.Count - 1].Visible = Roles.IsUserInRole("Editor");
You want to show/hide an entire column instead of LinkButton control. Otherwise, unauthorized user will always see a column with blank cells which is odd.
The following example will hide an entire column.
Screen Shot (Authorize vs Unauthorized)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1"
runat="server"
DataKeyNames="QuestionID"
OnPreRender="GridView1_OnPreRender"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>'
runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
public class Question
{
public int QuestionID { get; set; }
public string KeyObjective { get; set; }
}
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = new List<Question>
{
new Question {QuestionID = 1, KeyObjective = "One"},
new Question {QuestionID = 2, KeyObjective = "Two"},
new Question {QuestionID = 3, KeyObjective = "Three"},
};
GridView1.DataBind();
}
}
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
bool isEditor = true; // Business logic here
if (isEditor)
{
// Enter correct column index.
GridView1.Columns[2].Visible = false;
}
}
}
Use the LinkButton like this, with the Visibility property set from a function in code behind.
<asp:LinkButton ID="Edit" Visible='<%# ShowEditBasedOnRole() %>' CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
And then in code behind the function that returns a bool
public bool ShowEditBasedOnRole()
{
if (Roles.IsUserInRole("Editor"))
{
return true;
}
else
{
return false;
}
}
One quick modification instead of accessing the column by index. it can be accessed using header text which would not affect the code even if new column is inserted before the accessed column in future the code snippet
protected void grdResults_OnPreRender(object sender, EventArgs e)
{
TemplateField FieldToAccess= grdResults.Columns.OfType<TemplateField>
().Where(f => f.HeaderText ==
"ValidityDate").FirstOrDefault();
if (role)
FieldToAccess.Visible = false;
}
I have a Gridview and inside I have another one nested GridView. When I press a plus button the nested GridView expands using a JavScript. The nested GridView expands on edit mode using TextBox controls. So when the user types on a TextBox would have the ability to update the cell using an update button. My problem is that when I press the update button the update occurs but not how I would expected. If for example the initial value of a cell was “My name is Peter” and I have done the edit “I don’t have a name” The new value that will be saved is exactly this: “My name is Peter, I don’t have a name”. The databind of the nested GridView occurs on the parent GridView DataBound event.
My code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnPageIndexChanging="gridView_PageIndexChanging"
AutoGenerateColumns="False" DataKeyNames="myitemID"
OnRowDataBound="GridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="../plus.png" />
<asp:GridView ID="nestedGridView" runat="server"
AutoGenerateColumns="False"
DataKeyNames="mynestedID">
<Columns>
<asp:TemplateField HeaderText="nestedID" Visible="false" ItemStyle-Width="20%"
SortExpression="nesteditemID">
<ItemTemplate>
<asp:Label ID="nesteditemID" runat="server" Text='<%# Bind("nesteditemID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="20%"
SortExpression="Name">
<ItemTemplate>
<asp:TextBox ID="name" TextMode="MultiLine" Width="80%" Rows="3" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:Panel ID="mypanel" runat="server">
<table>
<tr>
<td>
<asp:ImageButton ID="ImageButton2" OnClick="updatename_Click" ImageUrl="~/images/update.jpg" Width="15px" Height="15px" runat="server"></asp:ImageButton>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="myitemID" InsertVisible="False"
SortExpression="myitemID" Visible="False">
<ItemTemplate>
<asp:Label ID="myitemID" runat="server" Text='<%# Bind("myitemID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ItemName" ItemStyle-Width="20%"
SortExpression="ItemName">
<ItemTemplate>
<asp:Label ID="ItemName" runat="server" Text='<%# Bind("ItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
cs code:
protected void updatename_Click(object sender, EventArgs e)
{
GridViewRow masterrow = (GridViewRow)(sender as Control).Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent;
GridViewRow row = (GridViewRow)(sender as Control).Parent.Parent.Parent;
int index = row.RowIndex;
int mi = masterrow.RowIndex;
int i = index;
GridView nestedGridView = (GridView)GridView1.Rows[mi].FindControl("nestedGridView");
Label nestedID = (Label)nestedGridView.Rows[index].FindControl("nestedID");
int sbid = Convert.ToInt32(nestedID.Text);
TextBox name = (TextBox)nestedGridView.Rows[index].FindControl("name");
string myname = Convert.ToString(name.Text);
//update name with the new value
Nesteditem updatenesteditem = mylinqobjects.Nesteditems.Single(p => p.nesteditemID == sbid);
if (!string.IsNullOrEmpty(myname))
{
updatenesteditem.nesteditemName = myname;
mylinqobjects.SubmitChanges();
}
}
Replaced the current text by removing the old one.
string myname = name.Text.Substring(name.Text.LastIndexOf(",")+1);
Tried all possiblities, but due nested grid view rendering and its restrictions, we could do only like above.
Any others solutions, please provide.
I have a GridView inside an UpdatePanel and use javascript to toggle the visibility of a row when the user clicks on an expand button. There is quite a bit of information above the GridView, but I want only the information in the respective UpdatePanel to update so that the screen will stay as is, but the JavaScript call is causing an entire screen refresh and the window jumps back to the top.
The code I'm using for the GridView actually comes from the ExtGridView control on CodeProject (http://www.codeproject.com/Articles/12299/ExtGridView) - it turns the last asp:TemplateField of a GridView into a new row beneath the other items.
I'm new to JavaScript and fairly new to ASP.NET, so I may be missing something simple. Is there a way to keep the JavaScript refresh to just the respective UpdatePanel that caused it?
Here is the JavaScript code:
<script type="text/javascript">
//<![CDATA[
function TglRow(ctl)
{
var row = ctl.parentNode.parentNode;
var tbl = row.parentNode;
var crow = tbl.rows[row.rowIndex + 1];
var ihExp = ctl.parentNode.getElementsByTagName('input').item(0);
tbl = tbl.parentNode;
var expandClass = tbl.attributes.getNamedItem('expandClass').value;
var collapseClass = tbl.attributes.getNamedItem('collapseClass').value;
var expandText = tbl.attributes.getNamedItem('expandText').value;
var collapseText = tbl.attributes.getNamedItem('collapseText').value;
if (crow.style.display == 'none')
{
crow.style.display = '';
ctl.innerHTML = collapseText;
ctl.className = collapseClass;
ihExp.value = '1';
}
else
{
crow.style.display = 'none';
ctl.innerHTML = expandText;
ctl.className = expandClass;
ihExp.value = '';
}
}//]]>
</script>
And here is an excerpt from the GridView:
<asp:UpdatePanel ID="UpdatePanelChapter11" runat="server"
ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<cc1:ExtGridView ID="gvChapter11" runat="server" AutoGenerateColumns="False" DataSourceID="odsChapter11"
DataKeyNames="pkChapter11ID" ShowFooter="True" SkinID="GridViewSKin" Width="85%"
onrowcommand="gvChapter11_RowCommand"
onrowdatabound="gvChapter11_RowDataBound"
onrowupdating="gvChapter11_RowUpdating"
CollapseButtonCssClass="GridCollapseButton"
ExpandButtonCssClass="GridExpandButton" CollapseButtonText=""
ExpandButtonText="" onrowcreated="gvChapter11_RowCreated">
<Columns>
<asp:TemplateField HeaderText="Name of<br/>Party" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="tbName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
<br /><asp:RequiredFieldValidator ID="tbNameValidator" runat="server" ErrorMessage="*Name Required" ControlToValidate="tbName"
Display="Dynamic" CssClass="Error" ValidationGroup="SaveChapter11Validation"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
<br /><asp:RequiredFieldValidator ID="tbNameValidator" runat="server" ErrorMessage="*Name Required" ControlToValidate="tbName"
Display="Dynamic" CssClass="Error" ValidationGroup="NewChapter11Validation"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:LinkButton CssClass="Button" ID="SaveLink" runat="server" CommandName="Update" Text="Save" ValidationGroup="SaveChapter11Validation"></asp:LinkButton>
<asp:LinkButton CssClass="Button" ID="CancelLink" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton CssClass="Button" ID="EditLink" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton CssClass="Button" ID="DeleteLink" runat="server" CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you sure you want to delete this entry?');" ></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton CssClass="Button" ID="AddLink" runat="server" CommandName="Insert" Text="<<< Add" ValidationGroup="NewChapter11Validation"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Plan">
<EditItemTemplate>
<div class="ExtGridRow" style="vertical-align:top;">Plan: </div>
<asp:TextBox ID="tbPlan" runat="server" Text='<%# Bind("Plan") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<div class="ExtGridRow" style="vertical-align:top;">Plan: </div>
<asp:Label ID="Label9" runat="server" Text='<%# Eval("Plan") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<div class="ExtGridRow" style="vertical-align:top;">Plan: </div>
<asp:TextBox ID="tbPlan" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</cc1:ExtGridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvChapter11" EventName="DataBound" />
</Triggers>
</asp:UpdatePanel>
Well shoot... a little more playing around with the ExtGridView code and I figured it out. The expand/toggle button that calls the javascript also had an HRef assigned, acting as a link, so when it was clicked it would not only call the JavaScript but also acted as if a link was clicked, causing the page refresh.
The culprit code from the ExtGridView:
// ...
else if (RowType == DataControlRowType.DataRow || RowType == DataControlRowType.Footer)
{
_expCell = new TableCell();
_ctlExpand = new HtmlAnchor();
//_ctlExpand.HRef = "#"; -- Commenting this out worked!
_ctlExpand.Attributes["onclick"] = "TglRow(this);";
_ihExp = new HtmlInputHidden();
_ihExp.ID = "e" + this.DataItemIndex.ToString();
_expCell.Controls.Add(_ctlExpand);
_expCell.Controls.Add(_ihExp);
}
if (_expCell != null)
{
_expCell.Width = Unit.Pixel(20);
Cells.AddAt(0, _expCell);
}
I am trying to implement a VERY simple ASP.net page: A GridView that allows user to edit old entry or insert a new entry. One of the columns in the GridView is holiday, so I use Jquery's datepicker to allow user to select a date.
Here is the ASP.net code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:GridView ID="GridView1" runat="server" Height="300px"
ShowFooter="True"
AutoGenerateColumns="false"
OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
<asp:TextBox ID="txtEditDate" runat="server" Text='<%# GetDate(Eval("CAL_DT")) %>' OnLoad="DisplayDatePicker1" ReadOnly="true"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewDate" runat="server" OnLoad="DisplayDatePicker2" ReadOnly="true"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# GetDate(Eval("CAL_DT")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my DisplayDatePicker1 method, DisplayDatePicker2 would be very similar.
protected void DisplayDatePicker1(object sender, EventArgs e)
{
StringBuilder scriptText = new StringBuilder();
string clientID = (sender as TextBox).ClientID;
scriptText.Append("$(function() {");
scriptText.Append("var DateSelector1 = $('#" + clientID + "'); ");
scriptText.Append("DateSelector1.datepicker();");
scriptText.Append(" });");
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"DateScript1", scriptText.ToString(), true);
}
So far so good. User can see the popup Datepicker and pick a date when he/she clicks Edit in the GridView row. Howerver, The following is the problem
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtEditHoliday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditHoliday");
TextBox txtEditDate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditDate");
DropDownList dpdCountry = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("dpdCountry");
//txtEditDate.Text is not set,
}
txtEditDate.Text still contains the old date. The value selected by user via JQuery datepicker is not being passed to the txtEditDate.Text Please help! I spent many hours to search the internet but have not found any solutions.
To get the new, revised values - use :
e.NewValues
(from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewupdateeventargs.aspx)