Populate textbox from database or label - c#

I'm having trouble figuring this out and it shouldn't be too difficult. I want to populate my textbox from my database or from the label (The labels are pulling the information from the database already, so essentially copying what's in the label to the textbox). I'm using a GridView and here is the code that I've been trying:
C#:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox timeR = GridView1.Rows[i].FindControl("rTime") as TextBox;
Label timeRL = GridView1.Rows[i].FindControl("labelRunScore") as Label;
if (timeR.Text == "")
{
timeR.Text = timeRL.Text;
}
}
.aspx:
<asp:TemplateField HeaderText = "Run Time">
<ItemTemplate>
<asp:Label ID="labelRunScore" Visible="true" runat="server" Text='<%# Eval("rTime") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Run Time">
<ItemTemplate>
<div style="display:none"> <asp:TextBox ID="rTime" runat="server" type="number" Text='<%# Eval("rTime") %>' ></asp:TextBox></div>
<input onblur="document.getElementById('<%# ((GridViewRow)Container).FindControl("rTime").ClientID %>').value = this.value"
type="number" style="width: 100px; height: 31px;" />
</ItemTemplate>
</asp:TemplateField>

Related

Why Rowcommand event of a gridview is not getting fired ?

I am facing a kind of weird problem.
Problem:
When I click a link button inside a grid view then RowCommand event of a grid view is getting fired when deployed on a localhost but not when deployed on the IIS i.e. client system. I have also tried a link button inside grid view but that's also not getting fired.
Solution: (Temporary)
When I disabled ValidateRequest on the top of the .aspx page. It worked.
What should I do?
So what can be the possible solution for it? I have googled but nothing good came up.
Code:
<asp:GridView ID="gvAppliedWorks" runat="server" OnRowCommand="gvAppliedWorks_RowCommand" AutoGenerateColumns="false" DataKeyNames="AppliedWorkID, ContractorID" EmptyDataText="No Data Found"
CssClass="table table-responsive table-bordered table-striped" OnRowDataBound="gvAppliedWorks_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Form No">
<ItemTemplate>
<asp:Literal ID="liFormNo" runat="server" Text='<% #Eval("FormNo")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company Name">
<ItemTemplate>
<asp:Literal ID="liCompanyName" runat="server" Text='<% #Eval("Name")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Financial Bid">
<ItemTemplate>
<asp:Label ID="txtBidAmount" runat="server" CssClass="control-label" Text='<% # string.Format("{0:n2}", Eval("FinancialMoney").ToString())%>' />
%
<asp:Label ID="ddlBidPer" runat="server" CssClass="control-label" Text='<%# Eval("AboveBelow").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Awarded Percentage">
<ItemTemplate>
<div class="pull-left">
<asp:HiddenField ID="hdnIsAwarded" Value='<%# Eval("IsAwarded") %>' runat="server" />
<asp:TextBox ID="txtAwardedBid" Text='<%#Eval("AwardedBid")%>' Style="width: 70px !important;" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="pull-left" style="margin-top: 7px">
% <%# Eval("AboveBelow").ToString() %>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="txtRemarks" Text='<%#Eval("Remarks")%>' runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Award Tender">
<ItemTemplate>
<asp:LinkButton ID="lnkAward" runat="server"
CommandArgument='<%# Eval("AppliedWorkID") %>' CommandName="award"
CssClass="btn btn-sm btn-danger" Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>'
Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' CausesValidation="false" Text="Award"></asp:LinkButton>
<ajax:ConfirmButtonExtender ID="cbe" runat="server" DisplayModalPopupID="mpe" TargetControlID="lnkAward">
</ajax:ConfirmButtonExtender>
<ajax:ModalPopupExtender ID="mpe" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkAward" OkControlID="btnYes"
CancelControlID="btnNo" BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
<div class="header">
Confirmation
</div>
<div class="body">
Are you sure to Award this Work?
</div>
<div class="Popupfooter" align="right">
<asp:Button ID="btnYes" CssClass="btn btn-sm btn-danger" runat="server" Text="Yes" />
<asp:Button ID="btnNo" CssClass="btn btn-sm btn-primary" runat="server" Text="No" />
</div>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText='Action'>
<ItemTemplate>
<asp:LinkButton ID="btnBlackList" runat="server" OnClick="btnBlackList_Click" Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>' Text='Defective'
CssClass="" ToolTip="Blacklist"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**.cs**
protected void gvAppliedWorks_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
// GridViewRow gr = ((GridViewRow)((Control)sender).Parent.Parent);
if (e.CommandName == "award")
{
GridViewRow gr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int AppliedWorkID = e.CommandArgument.ToInt32(); //gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
TextBox txtAwardedBid = gr.FindControl("txtAwardedBid") as TextBox;
TextBox txtRemarks = gr.FindControl("txtRemarks") as TextBox;
Label txtBid = gr.FindControl("txtBidAmount") as Label;
Label lblAboveBelow = gr.FindControl("ddlBidPer") as Label;
string AboveBelow = lblAboveBelow.Text;
Decimal BidAmount = txtBid.Text.ToDecimal();
if (String.IsNullOrEmpty(txtRemarks.Text))
{
Utility.Msg_Error(this.Master, "Remarks Required!!!");
return;
}
Decimal AwardedBid = string.IsNullOrEmpty(txtAwardedBid.Text.Trim()) ? 0 : txtAwardedBid.Text.Trim().ToDecimal();
string Remarks = txtRemarks.Text;
if (AwardedBid != BidAmount)
{
Utility.Msg_Error(this.Master, "Financial Bid must be equal to Awarded Percentage");
return;
}
if (ClsTender.IsReceivedSubMainOffice(AppliedWorkID, LoginUserID, AwardedBid, Remarks, BidAmount, AboveBelow))
{
Utility.Msg_Success(this.Master, "Work Awarded Successfully!!!");
fill_gvAppliedWorks(labNitNo.Text.Replace("NIT No :", "").ToInt32(), labWorkNo.Text.Replace("Work No :", "").ToInt32());
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
It sounds like your page is trying to submit what it thinks is potentially dangerous content if setting the ValidateRequest = false solves the issue. Is it possible that one of the controls on your page is sending html or something like that?
If one of your controls needs to send HTML then you can overcome this by adding an attribute to your model.
[AllowHtml]
[Required]
public string article_content { get; set; }
This will allow html to be entered into the control.

how to set compare validatior for footer table text boxes?

I have a grid view with two footer text boxex,
<asp:GridView ID="grdmaster" runat="server" AutoGenerateColumns="false" ShowFooter="true" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="txtdescription" runat="server" > </asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" Font-Bold="true" runat="server" Text="Total" > </asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Debit">
<ItemTemplate>
<asp:TextBox ID="txtdebit" runat="server" AutoPostBack="true" OnTextChanged="txtdebit_TextChanged"> </asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtdebit1" Font-Bold="true" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Credit">
<ItemTemplate>
<asp:TextBox ID="txtcredit" runat="server" AutoPostBack="true" OnTextChanged="txtcredit_TextChanged"> </asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtcredit2" Font-Bold="true" runat="server"></asp:Text>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btndelete" runat="server" class="btn red icn-only" OnClick="btndelete_Click"><i class="icon-remove icon-white"></i> </asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here I want to compare the footer Textebox txtdebit1 and txtcredit2 values are same or not.How can I set compare validator for.I followed some methods from google but got error message like Compare validator could not find control to validate text box.Is it possible to set compare validator for footer table text box?
Please try below,
protected void grdmaster_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridFooterItem)
{
GridDataItem item = (GridDataItem)e.Item;
TextBox txtdebit1 = item.FindControl("txtdebit1") as TextBox;
TextBox txtcredit2 = item.FindControl("txtcredit2") as TextBox;
TableCell cell = (TableCell)txtdebit1.Parent;
CompareValidator val = new CompareValidator();
val.ControlToCompare = txtcredit2.ID;
val.ControlToValidate = txtdebit1.ID;
val.Operator = ValidationCompareOperator.LessThan;
val.Display = ValidatorDisplay.Dynamic;
val.ErrorMessage = "Error message";
cell.Controls.Add(val);
}
}

How do i add footertemplate to gridview with option for expand and collapse datarows?C#/ASP.NET

Hi i want to make a footertemplate which can expand and collapse results like this image example in other topic: How do I add FooterTemplate to GridView with BoundFields
I want for default show 1 result, and after clicking in a icon on footertemplate show me more results like 4 or 5, i can show the code, thanks in advance.
The same work i have done on my project! I am pasting that work here. Please go through it, it might help you solving your problem
ASPX:
<asp:GridView Width="100%" border="1" ID="gwProfit" RowStyle-Wrap="true" runat="server" AutoGenerateColumns="false" AlternatingRowStyle-CssClass="alternaterow" RowStyle-VerticalAlign="Bottom" ShowFooter="True" HeaderStyle-Wrap="true" OnRowCommand="gwProfit_RowCommand" OnRowDataBound="gwProfit_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Start Date">
<ItemTemplate>
<div class="input-append">
<asp:TextBox class="input_disabled" ID="txtStartDate" runat="server" Width="110px" Height="22px" Text='<%# Bind("StartDate","{0}") %>'>
</asp:TextBox>
<button class="btn123" ID="ImgStartDate" runat="server" type="button" style="height:25px;">
<i class="icon-calendar"></i>
</button>
</div>
<ajaxToolkit:CalendarExtender ID="StartDate" runat="server" TargetControlID="txtStartDate" PopupButtonID="ImgStartDate" Format="dd-MMM-yyyy">
</ajaxToolkit:CalendarExtender>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox class="input_disabled" ID="txtNewStartDate" runat="server" Width="110px" Height="22px">
</asp:TextBox>
<button class="btn123" ID="ImgStartDate" runat="server" type="button" style="height:25px;">
<i class="icon-calendar"></i>
</button>
</div>
<ajaxToolkit:CalendarExtender ID="StartDate" runat="server" TargetControlID="txtNewStartDate"
PopupButtonID="ImgStartDate" Format="dd-MMM-yyyy">
</ajaxToolkit:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<asp:TextBox class="input_disabled" ID="txtEndDate" runat="server" Width="110px" Height="22px" Text='<%# Bind("EndDate","{0}") %>'>
</asp:TextBox>
<button class="btn123" ID="ImgEndDate" runat="server" type="button" style="height:25px;">
<i class="icon-calendar"></i>
</button>
<ajaxToolkit:CalendarExtender ID="EndDate" runat="server" TargetControlID="txtEndDate"
PopupButtonID="ImgEndDate" Format="dd-MMM-yyyy">
</ajaxToolkit:CalendarExtender>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox class="input_disabled" ID="txtNewEndDate" runat="server" Width="110px" Height="22px">
</asp:TextBox>
<button class="btn123" ID="ImgEndDate" runat="server" type="button" style="height:25px;">
<i class="icon-calendar"></i>
</button>
<ajaxToolkit:CalendarExtender ID="EndDate" runat="server" TargetControlID="txtNewEndDate"
PopupButtonID="ImgEndDate" Format="dd-MMM-yyyy">
</ajaxToolkit:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Profit Per Unit">
<ItemTemplate>
<asp:TextBox class="input_disabled" ID="txtProfitPerUnit" Width="100px" Height="22px" runat="server" Text='<%# Bind("ProfitPerUnit","{0}") %>'> </asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox class="input_disabled" ID="txtNewProfitPerUnit" Width="100px" Height="22px" runat="server" Text="0"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ControlStyle-Width="14px" FooterStyle-Width="14px">
<ItemTemplate>
<input type="hidden" id="txtrec_status" name="txtrec_status" runat="server"/>
<asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete" ImageUrl="~/images/delete.gif" AlternateText="Delete" CommandArgument="<%# ((GridViewRow) Container).RowIndex%>" UseSubmitBehavior="False" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="btnAdd" runat="server" CommandName="Add" ImageUrl="~/images/add.png" AlternateText="Add" UseSubmitBehavior="False"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind:
protected void gwProfit_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (ViewState["dtStartDate"] != null)
dtStartDate = (DataTable) ViewState["dtStartDate"];
if (e.CommandName.Equals("Add"))
{
TextBox txtStartDate = (TextBox)gwProfit.FooterRow.FindControl("txtNewStartDate");
TextBox txtEndDate = (TextBox)gwProfit.FooterRow.FindControl("txtNewEndDate");
TextBox txtProfitPerUnit = (TextBox)gwProfit.FooterRow.FindControl("txtNewProfitPerUnit");
if (txtEndDate.Text == "" || txtStartDate.Text == "" || txtProfitPerUnit.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('Please Select Start Date, End Date And Profit Per Unit.')", true);
}
else
{
dtStartDate.Rows.Add(dtStartDate.NewRow());
dtStartDate.Rows[dtStartDate.Rows.Count - 1]["CurrencyDeatailID"] = -2;
dtStartDate.Rows[dtStartDate.Rows.Count - 1]["StartDate"] = objFunc.toDate(txtStartDate.Text);
dtStartDate.Rows[dtStartDate.Rows.Count - 1]["EndDate"] = objFunc.toDate(txtEndDate.Text);
dtStartDate.Rows[dtStartDate.Rows.Count - 1]["ProfitPerUnit"] = objFunc.toDecimal(txtProfitPerUnit.Text);
if (dtStartDate.Rows.Count >= 0&&dtStartDate.Rows[0]["CurrencyDeatailID"].ToString()=="-1")
{
dtStartDate.Rows[0].Delete();
if (dtStartDate.Rows.Count > 0 && dtStartDate.Rows[0].RowState == DataRowState.Deleted)
dtStartDate.Rows.RemoveAt(0);
}
ViewState["dtStartDate"] = dtStartDate;
Profit_LoadGrid();
}
}
else if (e.CommandName.Equals("Delete"))
{
int index = objFunc.toInt(e.CommandArgument.ToString());
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RemoveAt = gvr.RowIndex;
DataTable dt = new DataTable();
dt = (DataTable)ViewState["dtStartDate"];
dt.Rows.RemoveAt(RemoveAt);
dt.AcceptChanges();
ViewState["dtStartDate"] = dt;
Profit_LoadGrid();
}
}
It would be easy
Activate "AllowPaging" in your GridView.
Make Paging row invisible.
In every click of an icon increase "PageSize" for expanding or click of another icon decrease "PageSize" for collapsing.

Limiting javascript update to just an asp:UpdatePanel

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);
}

Gridview Validation

I am using Gridview and using Item Template text box. There are 5 text box and i am adding a new row dynamically on clicking on add row btn. in that row i have adding all text box which is empty. Now i want to validate that text box on btn click next.
now to do it?
I used required field validation its working for first time showing text box but when i am adding a new row text box its not causing the validation, I think there is some other way to give validation for dynamically added text box.
How could i validation my all dynamically added text box
Grid view which i am using..
<Columns >
<asp:TemplateField>
<ItemTemplate>
<div class="otherOthersTd">
<asp:Label ID="lblcnt" ForeColor="#136A96" Text='<%#Eval("Count") %>' runat="server" ></asp:Label>
<asp:Label ID="lblId" runat="server" text='<%#Eval("Id") %>' Visible="false"></asp:Label>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>' Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middle Name">
<ItemTemplate>
<asp:TextBox ID="txtMName" runat="server" Text='<%# Eval("MName") %>'
Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:TextBox ID="txtLName" runat="server" Text='<%# Eval("LName") %>'
Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Degree">
<ItemTemplate>
<asp:TextBox ID="txtDegree" runat="Server" Text='<%# Eval("Degree") %>'
Width="50px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:TextBox ID="txtTitle" runat="Server" Text='<%# Eval("Title") %>' Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox ID="txtEmail" runat="Server"
Text='<%# Eval("Email") %>' Width="88px" CausesValidation="True" ValidationGroup="a"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpr" runat="server" ErrorMessage="Invalid email id" ControlToValidate="txtEmail" ValidationGroup="a" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
<asp:Label ID="revexp" runat="server" > </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Institution">
<ItemTemplate>
<asp:TextBox ID="txtInstitution" runat="server" Text='<%#Eval("Institution") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:Button ID="btnNext" runat="server" ValidationGroup="a" CausesValidation="true" Text="Next" class="next btn" onclick="btnNext_Click"/>
<asp:TemplateField> <ItemTemplate>
<asp:Label ID="lblAuthor" runat="server" Text="Authorerror" Visible="false" ForeColor="Red" Font-Bold="True" Font-Size="X-Large">*</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="false" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<HeaderStyle Font-Bold="false" ForeColor="#136A96" />
</asp:GridView>
my code...
protected void GridView1_OnRowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals(""))
{
lstAuthors = (List<OtherAuthors>)Session["lstAuthors"];
if (lstAuthors.Count == 0)
{
OtherAuthors obj0 = new OtherAuthors();
obj0.Count = "Author 1:";
lstAuthors.Add(obj0);
}
int index=GridView1.Rows.Count-1;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox Name = GridView1.Rows[i].FindControl("txtName") as TextBox;
TextBox MName = GridView1.Rows[i].FindControl("txtMName") as TextBox;
TextBox LName = GridView1.Rows[i].FindControl("txtLName") as TextBox;
TextBox Degree = GridView1.Rows[i].FindControl("txtDegree") as TextBox;
TextBox Title = GridView1.Rows[i].FindControl("txtTitle") as TextBox;
TextBox Email = GridView1.Rows[i].FindControl("txtEmail") as TextBox;
TextBox Institution = GridView1.Rows[i].FindControl("txtInstitution") as TextBox;
if(Name!=null)
{
lstAuthors[i].Name = Name.Text;
lstAuthors[i].MName = MName.Text;
lstAuthors[i].LName = LName.Text;
lstAuthors[i].Degree = Degree.Text;
lstAuthors[i].Title = Title.Text;
lstAuthors[i].Email = Email.Text;
lstAuthors[i].Institution = Institution.Text;
}
}
OtherAuthors obj1 = new OtherAuthors();
obj1.Count = "Author "+(lstAuthors.Count+1).ToString()+":";
obj1.Name="";
lstAuthors.Add(obj1);
GridView1.DataSource = lstAuthors;
GridView1.DataBind();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows.Count - 1 == i)
GridView1.Rows[i].Cells[8].Visible = true;
else
GridView1.Rows[i].Cells[8].Visible = false;
}
Session["lstAuthors"] = lstAuthors;
}
MultipleModalitySelect1.hideChosebutton = true;
}
private bool IsValied()
{
bool error = false;
TextBox Name = GridView1.Rows[0].FindControl("txtName") as TextBox;
TextBox MName = GridView1.Rows[0].FindControl("txtMName") as TextBox;
TextBox LName = GridView1.Rows[0].FindControl("txtLName") as TextBox;
TextBox Degree = GridView1.Rows[0].FindControl("txtDegree") as TextBox;
TextBox Title = GridView1.Rows[0].FindControl("txtTitle") as TextBox;
TextBox Email = GridView1.Rows[0].FindControl("txtEmail") as TextBox;
TextBox Institution = GridView1.Rows[0].FindControl("txtInstitution") as TextBox;
Label lblAuthor = GridView1.Rows[0].FindControl("lblAuthor") as Label;
if (Name.Text.Length == 0 || LName.Text.Length == 0 || Degree.Text.Length == 0 ||Title.Text.Length == 0 || Email.Text.Length == 0 || Institution.Text.Length == 0)
{
lblAuthor.Visible = true;
error = true;
}
else
{
lblAuthor.Visible = false;
}
}
You have used the validation group's ValidationGroup="a" on your Next button, but you have not used that on the Required Field Validator. But you have used it in the Email validator.
You have to be consistent with the Validation control and whether to put validation on all controls and button controls for it to work.
<asp:Button ID="btnNext" runat="server" ValidationGroup="a" CausesValidation="true" Text="Next" class="next btn" onclick="btnNext_Click"/>
I think you should start a new page and test with a much smaller case scenario and get that working first. Then add more boxes.
If you still need help with that smaller page, post it for help - it will be easier for us to understand it.

Categories

Resources