how to enable disable validators based on page controls? - c#

I have a gridView as follows.
<asp:GridView ID="grvLocationCash" runat="server" AutoGenerateColumns="false" CssClass="gridtable" DataKeyNames="LocationId">
<Columns>
<asp:BoundField HeaderText="Location Name" DataField="LocationName" />
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" CssClass="txtbox" Visible="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAmount" runat="server" ControlToValidate="txtAmount" ErrorMessage="Please enter the Amount" Display="Dynamic" SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rgvAmount" runat="server" ControlToValidate="txtAmount" ValidationExpression="^\d+$" ErrorMessage="Please enter whole numbers only" Display="Dynamic" SetFocusOnError="true"></asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and a save button with the following code.
<asp:Button ID="btnLocationAmountList" runat="server" OnClick="btnLocationAmountList_Click" Text="Save" Width ="100px" />
after the gridview is bound, there are about 20 rows in it.
When I type in numbers into the text box of the first row and press Enter key to go to second text box, the Required Field Validator is triggered for all the other 19 rows.
But, if I type numbers into the first text box and mouse click on the next text box, the RequiredFieldValidator is not triggered.
The page must be validated only if the Save button is clicked. Values must be entered for all the textboxes before save, and all the values must be integer only. (11,125,6589 etc).
How to enable disable validators for a particular control?
UPDATE: here is the page_load event code in my class file.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
FinanceServiceRef.FinanceServiceClient obj = new FinanceServiceRef.FinanceServiceClient("WSHttpBinding_IFinanceService");
var ds = obj.ViewLocationAmountCashManagement();
grvLocationCash.DataSource = ds;
grvLocationCash.DataBind();
}

You need to handle the onkeydown in each text box in each ItemTemplate, like this:
onkeydown = "return (event.keyCode!=13);"
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" CssClass="txtbox"
Visible="true"
onkeydown = "return (event.keyCode != 13);">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
Note: The Enter key has a keyCode value of 13.

Did you try using Validation Group property?
<asp:GridView ID="grvLocationCash" runat="server" AutoGenerateColumns="false" CssClass="gridtable" DataKeyNames="LocationId">
<Columns>
<asp:BoundField HeaderText="Location Name" DataField="LocationName" />
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" CssClass="txtbox" Visible="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAmount" runat="server" ControlToValidate="txtAmount" ErrorMessage="Please enter the Amount" Display="Dynamic" SetFocusOnError="true" ValidationGroup="save"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rgvAmount" runat="server" ControlToValidate="txtAmount" ValidationExpression="^\d+$" ErrorMessage="Please enter whole numbers only" Display="Dynamic" SetFocusOnError="true" ValidationGroup="save"></asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnLocationAmountList" runat="server" OnClick="btnLocationAmountList_Click" Text="Save" Width ="100px" ValidationGroup="save" />

Related

Unable to maintain data inside gridview across postback when used inside an user control

I've a textbox that is present inside a GridView that itself is a part of user control and I'm dynamically loading this user control on page_Init.
The controls in my user control are a DropDown, a TextBox and a GridView.
Now DropDown and TextBox are able to retain values across postback but textboxes inside the GridView are not retaining the values.
Adding User Control on page init:
if (postBackCntrl.Contains("AddUserControlButton"))
{
UserControl newGrid = (UserControl)LoadControl("~/UserControl.ascx");
newGrid.ID = "test" + gridList.Count;
gridList.Add(newGrid);
}
GridView Code: TextBoxes inside GridView ItemTemplate not able to retain values across postback:
<asp:GridView runat="server" ID="grdUser" CssClass="GridTable" Width="90%" AutoGenerateColumns="false"
ShowFooter="true" OnDataBound="MergeGridViewFooter">
<Columns>
<asp:TemplateField HeaderText="ContactUs">
<ItemTemplate>
<asp:TextBox ID="txtContactUs" runat="server" CssClass="textbox" Height="60px" TextMode="MultiLine"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnaddrow" runat="server" Text="Add Row" CssClass="ui-button jquery-ui" Style="font-size: 12px" OnClick="btnaddrow_Click" />
<asp:Button ID="btnDelRowAddress" runat="server" Text="Delete Row" CssClass="ui-button jquery-ui" Style="font-size: 12px" OnClick="btnDelRowAddress_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Definition">
<ItemTemplate>
<asp:TextBox ID="txtDefinition" runat="server" TextMode="MultiLine" Height="60px" CssClass="textbox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine" Height="60px" CssClass="textbox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Why asp.net c# ValidationSummary displays multiple message box?

Here's the thing. I have a ASP.NET Web Application in C#. In the Default.aspx I have an UpdatePanel containing all the elements. There, I have three validators associated with a TextBox, 4 RadioButton (two belong two one group and the other two to another group) and for each group I have a validator in order to verify if one element was checked for each group. For all RadioButton the AutoPostBack is set to "True" because when the "No" option is selected for both groups then I will enable a multi-line TextBox so the user can input some text. There's also a ValidationSummary at the end that displays error messages in a pop-up box and in the page as well. The main issue is the following: if I first select the two options from the RadioButtons and then click in the submit button, without input any text in the TextBox with the 3 validators, I will get 3 pop-up error messages. And more interesting, if I select after the 3 pop-up error messages another option from any of the RadioButton groups, I will get 4 pop-up error messages. I have a guess that it has to do with the AutoPostBack attribute of the RadioButton because it happens when I click them, but I don't know why or how to fix it.
Here's the code for Default.aspx:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="M-DCPS 7-digit Student ID#:"></asp:Label>
<asp:TextBox ID="studentIDtbox" runat="server" MaxLength="7" Width="6%" CausesValidation="false"></asp:TextBox>
<asp:RequiredFieldValidator Font-Size="Large" ID="RequiredFieldValidatorAccount" runat="server" ControlToValidate="studentIDtbox"
ErrorMessage="ID# required" ForeColor="Red">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator Font-Size="Large" ID="RegularExpressionValidator2" runat="server" ControlToValidate="studentIDtbox" ErrorMessage=" ID requires 7 digits" ValidationExpression="^[\s\S]{7,}$" ForeColor="Red">*</asp:RegularExpressionValidator>
<asp:RegularExpressionValidator Font-Size="Large" ID="RegularExpressionValidator1" runat="server" ControlToValidate="studentIDtbox"
ErrorMessage=" ID only accepts numbers" ValidationExpression="^\d+$" ForeColor="Red">*</asp:RegularExpressionValidator>
<asp:Label ID="Label2" runat="server" Text="Paper Form:"></asp:Label>
<asp:DropDownList ID="paperForm" runat="server"></asp:DropDownList>
<asp:Label ID="Label3" runat="server" Text="Paper Accommodation:"></asp:Label>
<asp:DropDownList ID="paperType" runat="server"></asp:DropDownList>
<asp:CustomValidator Font-Size="Large" runat="server" ID="cvIEP" OnServerValidate="cvIEP_ServerValidate"
Enabled="true" Display="Dynamic" SetFocusOnError="true" ErrorMessage="You must select at least one item for documentation on IEP/Section 504." ForeColor="Red">*</asp:CustomValidator>
<asp:Label ID="Label4" runat="server" Text="Paper is documented?"></asp:Label>
<asp:RadioButton ID="iepYesRb" runat="server" GroupName="IEPRequirement" Text="Yes" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:RadioButton ID="iepNoRb" runat="server" GroupName="IEPRequirement" Text="No" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:CustomValidator Font-Size="Large" runat="server" ID="cvRuse" OnServerValidate="cvRuse_ServerValidate"
Enabled="true" SetFocusOnError="true" ErrorMessage="You must select at least one item for regular use." ForeColor="Red">*</asp:CustomValidator>
<asp:Label ID="Label5" runat="server" Text="Is it used regularly?"></asp:Label>
<asp:RadioButton ID="ruseYesRb" runat="server" GroupName="RegularUse" Text="Yes" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:RadioButton ID="ruseNoRb" runat="server" GroupName="RegularUse" Text="No" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:Label ID="Label6" runat="server" Text="Provide other evidence if two 'No' where selected."></asp:Label>
<asp:TextBox ID="evidenceTbox" Style="height: 130px" runat="server" TextMode="MultiLine" Width="100%" Enabled="false"></asp:TextBox>
<asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submit_OnClick" />
<asp:ValidationSummary ID="valTest" runat="server" ShowMessageBox="true" BackColor="LightYellow" ForeColor="Red" Width="100%" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="submitButton" />
<asp:AsyncPostBackTrigger ControlID="iepYesRb" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="iepNoRb" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="ruseYesRb" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="ruseNoRb" EventName="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>
And here's the code for Default.aspx.cs:
protected void rButton_CheckedChanged(object sender, EventArgs e)
{
evidenceTbox.Enabled = iepNoRb.Checked && ruseNoRb.Checked;
}
protected void cvIEP_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = iepNoRb.Checked || iepYesRb.Checked;
}
protected void cvRuse_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = ruseNoRb.Checked || ruseYesRb.Checked;
}
protected void submit_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('Record inserted properly')", true);
}
}
Any help will be appreciated and critics will be very welcome. Thanks.

RowEditing command not firing

I have a gridview that adds rows in the footertemplate that works fine. I want to add RowEditing and RowDeleting to the grid.
I added the RowEditing method but when I click the 'Edit' Button, the add row is displayed in the footer as if it is the "Add Row' command.
When I created a prototype of a grid, I had a column just for editing and it was a commandfield. WHen you click the button, the row would change so that all of the fields were editable. How can I do that when the field is an ItemTemplate field?
This is my markup:
<asp:GridView ID="MappingGridView" runat="server" AllowSorting="True" AutoGenerateColumns="False" Caption="Enrollment Mapping Information" CaptionAlign="Top"
CssClass="grid" HorizontalAlign="Left" ShowFooter="True" AllowPaging="True" PageSize="4" ShowHeaderWhenEmpty="true" OnPageIndexChanging="MappingGridView_PageIndexChanging"
OnRowDataBound="MappingGridView_RowDataBound" OnRowCommand="MappingGridView_RowCommand" Width="1051px" OnRowEditing="MappingGridView_RowEditing">
<Columns>
<asp:TemplateField HeaderText="MappingID" SortExpression="mgvMappingID">
<ItemTemplate>
<asp:Label ID="mgvLblMappingID" runat="server" Text='<%# Bind("EnrollmentMappingID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SectionID">
<EditItemTemplate>
<asp:TextBox ID="mgvDdlSectionID" runat="server" Text='<%# Bind("SectionID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="mgvLblSectionID" runat="server" Text='<%# Bind("SectionID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="mgvInsertSectionID" runat="server" ReadOnly="true" Text="" Width="90%"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SchoologyCourseID" SortExpression="mgvSchoologyCourseID">
<EditItemTemplate>
<asp:TextBox ID="mgvEditSchoologyCourseID" runat="server" Text='<%# Bind("SchoologyCourseID") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqFieldValEditSchoologyCourseID" ControlToValidate="mgvEditSchoologyCourseID" runat="server"
ErrorMessage="Required field." ValidationGroup="MappingGrid" Display="Dynamic"
CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegExpValEditSchoologyCourseID" ControlToValidate="mgvEditSchoologyCourseID" runat="server"
ErrorMessage="Enter only integers." ValidationGroup="MappingGrid" ValidationExpression="^\d+$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="mgvLblSchoologyCourseID" runat="server" Text='<%# Bind("SchoologyCourseID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="mgvInsertSchoologyCourseID" runat="server" Width="90%"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqFieldValSchoologyCourseID" ControlToValidate="mgvInsertSchoologyCourseID" runat="server"
ErrorMessage="Required field." ValidationGroup="MappingGrid" Display="Dynamic"
CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegExpValSchoologyCourseID" ControlToValidate="mgvInsertSchoologyCourseID" runat="server"
ErrorMessage="Enter only integers." ValidationGroup="MappingGrid" ValidationExpression="^\d+$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CECityActivityID" SortExpression="mgvCECityActivityID">
<EditItemTemplate>
<asp:TextBox ID="mgvEditCECityActivityID" runat="server" Text='<%# Bind("CECityActivityID") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpValEditCECityID" ControlToValidate="mgvEditCECityActivityID" runat="server"
ErrorMessage="Enter 0-9, A-F, and hyphens. Maximum length is 50." ValidationGroup="MappingGrid" ValidationExpression="^[0-9A-Fa-f-]{0,50}$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="mgvLblCECityActivityID" runat="server" Text='<%# Bind("CECityActivityID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="mgvInsertCECityActivityID" runat="server" Width="90%"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpValCECityID" ControlToValidate="mgvInsertCECityActivityID" runat="server"
ErrorMessage="Enter only 0-9, A-F, and hyphens; maximum length is 50." ValidationGroup="MappingGrid" ValidationExpression="^[0-9A-Fa-f-]{0,50}$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active" SortExpression="mgvIsActive">
<EditItemTemplate>
<asp:DropDownList ID="mgvEditIsActive" runat="server" Text='<%# Bind("IsActive") %>'>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="mgvLblIsActive" runat="server" Text='<%# Bind("IsActive") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="mgvInsertIsActive" runat="server" Width="90%">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Max. Enrollment">
<EditItemTemplate>
<asp:TextBox ID="mgvEditMaxEnrollment" runat="server" Text='<%# Bind("MaxEnrollment") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpValEditMaxEnroll" ControlToValidate="mgvEditMaxEnrollment" runat="server"
ErrorMessage="Enter only integers." ValidationGroup="MappingGrid" ValidationExpression="^\d+$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="mgvLblMaxEnrollment" runat="server" Text='<%# Bind("MaxEnrollment") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="mgvInsertMaxEnrollment" runat="server" Width="90%"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpValMaxEnroll" ControlToValidate="mgvInsertMaxEnrollment" runat="server"
ErrorMessage="Enter only integers." ValidationGroup="MappingGrid" ValidationExpression="^\d+$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="mgvImgUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:Button>
<asp:Button ID="mgvImgCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:Button>
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="mgvEditButton" runat="server" CausesValidation="True" ValidationGroup="MappingGrid" CommandName="Edit" Text="Edit" Width="40%"></asp:Button>
<asp:Button ID="mgvDeleteButton" runat="server" CausesValidation="false" CommandName="Delete" Text="Delete" Width="40%"></asp:Button>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<FooterTemplate>
<asp:Button ID="mgvBtnAdd" runat="server" CommandName="Add" Text="Add Mapping" Width="90%" CausesValidation="true" ValidationGroup="MappingGrid" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<tr>
<td colspan="11" style="text-align:center;">
No mapping data was found for this section. Mappings can be added to this section by clicking the 'Add Mapping' Button.
</td>
</tr>
<tr>
<td></td>
<td><asp:TextBox ID="mgvInsertSectionID" runat="server" ReadOnly="true" Width="90%"></asp:TextBox></td>
<td><asp:TextBox ID="mgvInsertSchoologyCourseID" runat="server" Width="90%"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqFieldValSchoologyCourseIDEmpty" ControlToValidate="mgvInsertSchoologyCourseID" runat="server"
ErrorMessage="Required field." ValidationGroup="MappingGrid" Display="Dynamic"
CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegExpValSchoologyCourseIDEmpty" ControlToValidate="mgvInsertSchoologyCourseID" runat="server"
ErrorMessage="Enter only integers." ValidationGroup="MappingGrid" ValidationExpression="^\d+$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</td>
<td><asp:TextBox ID="mgvInsertCECityActivityID" runat="server" Width="90%"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpValCECityIDEmpty" ControlToValidate="mgvInsertCECityActivityID" runat="server"
ErrorMessage="Enter only 0-9, A-F, and hyphens; maximum length is 50." ValidationGroup="MappingGrid" ValidationExpression="^[0-9A-Fa-f-]{0,50}$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</td>
<td><asp:DropDownList ID="mgvInsertIsActive" runat="server" Width="90%">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList></td>
<td><asp:TextBox ID="mgvInsertMaxEnrollment" runat="server" Width="90%"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpValMaxEnrollEmpty" ControlToValidate="mgvInsertMaxEnrollment" runat="server"
ErrorMessage="Enter only integers." ValidationGroup="MappingGrid" ValidationExpression="^\d+$"
Display="Dynamic" CssClass="message-error">
</asp:RegularExpressionValidator>
</td>
<td><asp:Button ID="mgvBtnAddEmpty" runat="server" CommandName="Add" Text="Add Mapping" Width="90%" CausesValidation="true"
ValidationGroup="MappingGrid" />
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
This is my code behind:
protected void MappingGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
MappingGridView.EditIndex = e.NewEditIndex;
populateEnrollMappingGrid();
}
When I click the edit button, the RowEditing method is not called and the footer row displays the insert action.
How do I get the Edit button to make the row clicked editable?
UPDATED INFORMATION Page_Load
This is the Page_Load Method:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
//Get the Environment Setting to determine the database to access
txtBoxEnvironment.Text = CurrentEnvironment;
DAL.setCurrentEnvironment(CurrentEnvironment);
//Get All Section information from database
CSectionInfo.getData();
//Get All Mapping informatio from database
CEnrollMappingInfo.getData();
//Populate the Mapping grid
MappingGridView.DataSource = CEnrollMappingInfo.getInitialData();
//Populate the Drop Down Section List
populateDropDownSectionList(CEnrollMappingInfo.SelectedSectionID);
//Grid must be bound after the Dropdown List is set so the value in the footer can be determined
MappingGridView.DataBind();
//Populate the Section grid
SectionGridView.DataSource = CSectionInfo.getDataUsingSectionID(CEnrollMappingInfo.SelectedSectionID);
//Get Course information from database
populateCourseGrid();
//Populate the Drop Down Course List
populateDropDownCourseList(CSectionInfo.SelectedCourseID);
//Grid must be bound after the Dropdown List is set so the value in the footer can be determined
SectionGridView.DataBind();
}
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
Response.Redirect("~/Error.aspx");
}
}
Thanks.
Just a guess, you are databinding the GridView on every postback.
You have a Page_Load similar to:
protected void Page_Load(object sender, EventArgs e)
{
populateEnrollMappingGrid(); // a method where you assign the DataSource and call grid.DataBind()
}
Use the IsPostBack property:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
populateEnrollMappingGrid();
}
I corrected the problem...
In my markup, I set the Edit Button CausesValidation=true and ValidationGroup-MappingGrid which is what the insert validation is in the footer. To correct, I set the CausesValidation to false and removed the ValidationGroup.
I set these values in the Update Button field.
Work now!
Thanks.

I can't get the value of textbox from the footer row of gridview

i can't get the value of textbox from the footer row of gridview
<asp:GridView ID="GridView1" runat="server" Width="1214px"
AutoGenerateColumns="False" ShowFooter="true"
OnRowCommand="GridView1_RowCommand"
<Columns>
<asp:TemplateField HeaderText="Insert">
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name">
<EditItemTemplate>
<asp:Label ID="lblEditSName" runat="server" Text='<%#Eval("sname") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblSName" runat="server" Text='<%#Eval("sname") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSName" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and the code behind is........
i can't get the value of textbox from the footer row of gridview
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName==("AddNew"))
{
TextBox txtName =(TextBox) GridView1.FooterRow.FindControl("txtSName");
string strName=txtName.Text; //strName is Empty while i m enters data into the textbox txtSName
}
Posting this comment to help others who may encounter the same issue.
Make sure the grid is not loading again on post back.
code in the page load should look like this
if (!IsPostBack)
{
LoadGrid();
}
Your mark up is biting you.You are having two footer templates within a template field.
Do this
<asp:TemplateField HeaderText="Insert">
<ItemTemplate>
<asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
ImageUrl="~/images/Edit.png"Style="height: 16px" ToolTip="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete"
CausesValidation="false" OnClientClick="return confirm('Delete.Are you sure you want to delete?')"
ImageUrl="~/images/DeleteTS.png" Text="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="AddNewImgBtn" runat="server" ImageUrl="~/images/saveHS.png"
ToolTip="Add New" AlternateText="Add New" Width="16px" Height="16px"
CommandArgument="InsertNew" ImageAlign="AbsMiddle" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name">
<EditItemTemplate>
<asp:Label ID="lblEditSName" runat="server" Text='<%#Eval("sname") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblSName" runat="server" Text='<%#Eval("sname") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSName" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And then you can gracefully locate your footer row.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandArgument=="InsertNew")
{
GridView testGrid=(Gridview)sender;
TextBox txtName =(TextBox)testGrid.FooterRow.FindControl("txtSName");
string strName=txtName.Text;
}
}
See working example Example

Details view and field edit authorization

I am trying to utilize a details view and provide the edit feature for a few levels of user authorization. Basically level 1 users cannot update a predefined set of fields but level 2 users can update these fields. I had tried simply setting the field to visible=false when defining the EditTemplate and then in the DataBind I would test for authorization and make it visible=true if the user had privileges to update the field (see code example below). Worked like a charm, except I noticed that when level 1 users update the fields they are allowed to update, the visible=false fields would be set to null (overwritten) in the database. So, been trying various options not to have to duplicate the views etc.
code snippet:
aspx....
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level %>"
SortExpression="LevelId">
<EditItemTemplate>
<asp:DropDownList ID="LevelList" runat="server"
DataTextField="LevelDesc" DataValueField="LevelId">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level1 %>"
SortExpression="Level1Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level1" runat="server" Text='<%#
Bind("Level1Date", "{0:d}") %>' />
<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="Please enter a valid date (m/d/y)"
ControlToValidate="Level1" Operator="DataTypeCheck"
Type="Date" Display="Dynamic">
</asp:CompareValidator>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level2 %>"
SortExpression="Level2Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level2" runat="server" Text='<%#
Bind("Level2Date", "{0:d}") %>' />
<asp:CompareValidator ID="CompareValidator2" runat="server"
ErrorMessage="Please enter a valid date (m/d/y)"
ControlToValidate="Level2" Operator="DataTypeCheck"
Type="Date" Display="Dynamic">
</asp:CompareValidator>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level4 %>"
SortExpression="Level4Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level4" runat="server" Text='<%#
Bind("Level4Date", "{0:d}") %>' />
</Fields>
aspx.cs SNIPPET
<name>_DataBound(object sender, EventArgs e)
{
.
.
.
if (User.IsInRole("yyy") || User.IsInRole("xxx))
{
OfficialProfileInfo.Fields[2].Visible = true;
OfficialProfileInfo.Fields[3].Visible = true;
}
You must set the DataKeyNames property for the automatic updating, deleting, and inserting features of the DetailsView control to work.
While updating if some fields should not change, you can put them in the key.
if (User.IsInRole("yyy") || User.IsInRole("xxx))
{
OfficialProfileInfo.Fields[2].Visible = true;
OfficialProfileInfo.Fields[3].Visible = true;
}
else
{
OfficialProfileInfo.DataKeyNames = "Level4Date"
}
Note: DataKeyNames is a comma-seperated list of field names/

Categories

Resources