Dynamically created requiredfieldvalidator bypasses client side validation - asp.net

I am trying to add a required field validator to my page at runtime.
Nothing fancy there:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:ValidationSummary ID="ValidationSummary1"
runat="server" ShowMessageBox="True" ShowSummary="False" />
</form>
and # codebehind
protected void Page_Init(object sender, EventArgs e)
{
RequiredFieldValidator theValid = new RequiredFieldValidator();
theValid.ID = "0000" + "RFV";
theValid.ControlToValidate = TextBox1.ID;
theValid.ErrorMessage = "Message here"
theValid.Text = "*";
theValid.Display = ValidatorDisplay.Dynamic;
theValid.EnableClientScript = true;
theValid.EnableViewState = true;
theValid.SetFocusOnError = true;
theValid.Enabled = true;
theValid.Visible = true;
Page.Validators.Add(theValid);
form1.Controls.Add(theValid);
}
When I click the button it only validates server-side, but not client-side. What am I missing?
TIA.

You can to check your code with jquery.
function TextBoxValidate() {
$('input:[type="text"]:[id*="TextBox1"]').each(function () { var txtId = this.id; $('span').each(function () { if (this.controltovalidate == txtId) ValidatorValidate(this); }); });
}
function InitValidationOnClick()
{
$('input:[id*="Button1"]').each(function(){$(this).on('click', function(){TextBoxValidate(); return Page_IsValid;});});
// or other case
//$('form:[id*="form1"]').each(function(){$(this).on('submit', function(){TextBoxValidate(); return Page_IsValid;});});
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitValidationOnClick);
If validator exists in page it will validate on click (submit) event client-side.

Hello All Try This one For Radio Buttons Along With RequiredField Validator
Code
TableRow trow4 = new TableRow();
trow4.Style.Add("width", "100px");
TableCell tcel4 = new TableCell();
Label lb4 = new Label();
lb4.Text = Resources.QcLabelName.Gender;
tcel4.Controls.Add(lb4);
CSSCell(tcel4);
table.Rows.Add(trow4);
RadioButtonList rblist = new RadioButtonList();
rblist.ID = "rbtnmalendfemale";
rblist.Items.Add("Male");
rblist.Items.Add("Female");
tcel4.Controls.Add(rblist);
trow4.Cells.Add(tcel4);
table.Rows.Add(trow4);
rblist.Visible = true;
RequiredFieldValidator rFV5 = new RequiredFieldValidator();
TableCell tcl46 = new TableCell();
rFV5.ControlToValidate = "rbtnmalendfemale";
rFV5.ErrorMessage = "Gendor Selection Is Mandatory";
rFV5.Style.Add("color", "Red");
rFV5.ID = "Reqfield9";
tcl46.Controls.Add(rFV5);
trow4.Cells.Add(tcl46);
table.Rows.Add(trow4);
rFV5.Visible = true;******

Related

how to check the duplicate filename in asp:fileupload?

i have an updatepanel and inside of it the contenttemplate is an asp:FileUpload..now when i will try to choose the file i want to check the filename in the database..i know my database part but how will i call the function in the server like for asp:TextBox i can use OnTextChanged something like that..but for asp:FileUpload is there anything by which i can check the filename and without clicking the button add?? my code
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" AutoPostBack="true" OnLoad="filename_Changed" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
my aspx.cs code
protected void filename_Changed(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string tuname = tutorialupload.PostedFile.FileName;
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
if (grpIDreader.HasRows)
{
f1.Text = "Duplicate filename.Sorry.";
}
else
{
f1.Text = "";
}
objsqlconn.Close();
}
now when i will choose the file..i want to call this function filename_Changed() and it will give me the result whether the filename is present or not..so i want to do it without clicking my the add button??
You should use the has file property, when true do you DB check, something like this
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
// Before attempting to save the file, do something
else
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
Here is how you can detect the change in the selected file name using JavaScript through the FileUpload onChange event.
ASPX Page: Make sure to set EnablePageMethods = true in the ScriptManager object.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" OnChange="CheckFileName(this)" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
JavaScript:
function CheckFileName(oFile)
{
PageMethods.FileNameChecker(oFile.value, OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
lbl = document.getElementById('<%=f1.ClientID %>');
if (methodName == "FileNameChecker")
{
if (result == true)
{
lbl.innerHTML = 'Duplicate filename.Sorry.';
lbl.style.color = "red";
}
else
{
lbl.innerHTML = '';
}
}
}
C# Code-Behind: You can call a WebMethod to check if the new selected filename exists in the DB:
You need to reference the following:
using System.Web.Services;
Then add the following method and make sure you put [WebMethod] before method declaration:
[WebMethod]
public static bool FileNameChecker(string newFileName)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string x = newFileName.Substring(0,newFileName.LastIndexOf("\\"));
string tuname = newFileName.Substring(newFileName.LastIndexOf("\\") + 1, newFileName.Length - x.Length - 1);
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
bool found = false;
if (grpIDreader.HasRows)
found = true;
objsqlconn.Close();
return found;
}

PagedDataSource and UpdatePanel don't work together

I have a problem with PagedDataSource and UpdatePanel.When I use AsyncPostBackTrigger in my buttons, paging in my page disappear.
Here's asp code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="DataListGallery" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" OnItemDataBound="DataListGallery_ItemDataBound" >
<ItemTemplate>
<asp:HiddenField ID="FieldPhoneId" Value='<%# Eval("Phone_InfoID") %>' runat="server" />
<asp:ImageButton ID="btnShop" OnClick="btnShop_Click" ImageUrl="images/cart.gif" CssClass="left_bt_item" title="header=[خريد] body=[ ] fade=[on]" runat="server" />
<asp:ImageButton CssClass="left_bt_item" title="header=[مورد علاقه] body=[ ] fade=[on]" OnClick="btnFavourite_Click" ID="btnFavourite" ImageUrl="images/unfav.png" runat="server" />
.
.
.
Here's C# code(load event):
protected void Page_Load(object sender, EventArgs e)
{
//http://www.aspdotnetfaq.com/Faq/how-to-determine-whether-an-asynchronous-partial-postback-has-occurred-on-page.aspx
// get a reference to ScriptManager and check if we have a partial postback
if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
{
// partial (asynchronous) postback occured
// insert Ajax custom logic here
}
// enable property is re-creating page controls
else if (!Page.IsPostBack || enable)
{
//enable = false;
if (Page.Request["Page"] != null || Page.Request["Page"] != "")
{
.
.
.
And a button with AsyncPostBackTrigger:
protected void btnFavourite_Click(object sender, ImageClickEventArgs e)
{
// Access to real ImageButton from repeater
ImageButton ib = (ImageButton)sender;
HiddenField hf = (HiddenField)ib.Parent.FindControl("FieldPhoneId");
Favourite objFav = new Favourite(Convert.ToInt32(hf.Value));
Guid userId = objFav.GetUserIdFromUserName(User.Identity.Name);
using (var context = new MobileGalleryEntities())
{
try
{
// Delete favorited
if (objFav.HadFavorited(User.Identity.Name))
{
int phoneInfoId = Convert.ToInt32(Convert.ToInt32(hf.Value));
// Remove favourite
objFav.RemoveFromFavourite(userId);
// Change image
ib.ImageUrl = "~/images/unfav.png";
}
// Add favorite
else
{
// Add phone
objFav.AddToFavourite(userId);
// Change image
ib.ImageUrl = "~/images/favs.gif";
}
}
catch (Exception ex)
{
}
}
}
Here's DataBound event:
protected void DataListGallery_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (User.Identity.IsAuthenticated)
{
try
{
// Get LoginView for access to ImageButton on it.
var loginView = e.Item.FindControl("LoginView1");
ImageButton btnCom = (ImageButton)e.Item.FindControl("btnCompare");
//ImageButton btnFav = (ImageButton)loginView.FindControl("btnFavourite");
ImageButton btnFav = (ImageButton)e.Item.FindControl("btnFavourite");
btnFav.Visible = true;
ImageButton btnShop = (ImageButton)e.Item.FindControl("btnShop");
btnShop.Visible = true;
//HiddenField hf = (HiddenField)loginView.FindControl("FieldPhoneId");
HiddenField hf = (HiddenField)e.Item.FindControl("FieldPhoneId");
List<int> listFav = (List<int>)Session["Fav"];
if (listFav.Contains(int.Parse(hf.Value)))
btnFav.ImageUrl = "~/images/favs.gif";
}
catch(Exception ex)
{
}
}
else
{
ImageButton btnFav = (ImageButton)e.Item.FindControl("btnFavourite");
btnFav.Visible = false;
ImageButton btnShop = (ImageButton)e.Item.FindControl("btnShop");
btnShop.Visible = false;
}
}
When I fire btnFavourite button, paging in my page disapear. but when i use FullPostBack it's work.
Notice that when I use FullPostBack, I re-create controls such as paging control and other control but when I use AsyncPostBackTrigger I didn't re-create controls.
What am I doing?
Thanks.
I have to re-create controls again the same as FullPostBack.

Getting values from textbox in the repeater in button click event

I have a TextBox in a repeater that is populated from the database in the ItemDataBound event. When I tried to get the text inside the TextBox in a Button_Click event I found the TextBox.Text empty. How can I get the Text?
foreach (RepeaterItem repeated in repEdit.Items)
{
DropDownList drp = (DropDownList)FindControlRecursive(repeated, "drpdown");
TextBox txt = (TextBox)FindControlRecursive(repeated, "txt");
CheckBox chk = (CheckBox)FindControlRecursive(repeated, "chk");
if (drp != null && !string.IsNullOrEmpty(drp.Attributes["ID"]))
{
loc.GetType().GetProperty(drp.Attributes["ID"].Split('#')[0] + "ID").SetValue(loc, int.Parse(drp.SelectedValue), null);
}
if (txt != null && !string.IsNullOrEmpty(txt.Attributes["ID"]))
{
if (txt.Attributes["ID"].Contains("#int"))
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, int.Parse(txt.Text), null);
}
else if (txt.Attributes["ID"].Contains("#decimal"))
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, decimal.Parse(txt.Text), null);
}
else
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, txt.Text, null);
}
}
if (chk!=null && !string.IsNullOrEmpty(chk.Attributes["ID"]))
{
loc.GetType().GetProperty(chk.Attributes["ID"].Split('#')[0]).SetValue(loc, chk.Checked, null);
}
}
HTML
<asp:Repeater ID="repEdit" runat="server" OnItemDataBound="repEdit_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Visible="false"></asp:Label>
<asp:TextBox ID="txt" runat="server" Visible="false"></asp:TextBox>
<asp:CheckBox ID="chk" runat="server" Visible="false" />
<asp:DropDownList ID="drpdown" runat="server" Visible="false">
</asp:DropDownList>
<br />
</ItemTemplate>
</asp:Repeater>
Here is the itemdatabound event
protected void repEdit_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Label name = e.Item.FindControl("lblName") as Label;
TextBox text = e.Item.FindControl("txt") as TextBox;
CheckBox chk = e.Item.FindControl("chk") as CheckBox;
DropDownList drp = e.Item.FindControl("drpdown") as DropDownList;
Button but = e.Item.FindControl("butEdit") as Button;
//butEdit.Visible = true;
if (but != null)
{
but.Visible = true;
}
if (e.Item.ItemType == ListItemType.Item)
{
KeyValuePair<string, Dictionary<int, string>> kvp = (KeyValuePair<string, Dictionary<int, string>>)e.Item.DataItem;
if (name != null)
{
if (kvp.Key.Contains("#datetime"))
{
return;
}
name.Visible = true;
name.Text = kvp.Key.Split('#')[0].ToString();
}
if (kvp.Key.Contains("#int") || kvp.Key.Contains("#decimal"))
{
text.Visible = true;
text.ID = kvp.Key;
text.EnableViewState = true;
text.Attributes["ID"] = kvp.Key;
text.Text = kvp.Value[0].ToString();
if (kvp.Key.Split('#')[0] == "ID")
{
text.Enabled = false;
}
}
Here is your Repeater. It has a PlaceHolder and Button.
<asp:Repeater ID="rpNotifications" runat="server"
OnItemDataBound="rpNotifications_ItemDataBound">
<ItemTemplate>
<asp:PlaceHolder ID="commentHolder" runat="server"></asp:PlaceHolder>
<asp:Button runat="server" ID="btnComment"
Text="Comment" CssClass="btn blue"
OnClick="btnComment_Click" CommandArgument='<%# Eval("id") %>' />
</ItemTemplate>
</asp:Repeater>
The button has the command argument set as the Id of the data I am binding to it.
Next here is where you need to Bind your Repeater. If you don't Bind it in the Page_Init the resulting values in the dynamically created controls will be lost.
protected void Page_Init(object sender, EventArgs e)
{
rpNotifications.DataSource = {datasource-here}
rpNotifications.DataBind();
}
And here is why (Image from: http://msdn.microsoft.com/en-us/library/ms972976.aspx)
Dynamically Create Control on ItemDataBound
You will need to add the textbox to the placeholder as this is the only way to dynamically assign an ID to the control.
protected void rpNotifications_ItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem)
{
Common.Models.Item item = (Common.Models.Item)e.Item.DataItem;
// Create new Control
TextBox txtComment = new TextBox();
txtComment.ID = String.Format("txtComment{0}", item.id.ToString());
// Ensure static so you can reference it by Id
txtComment.ClientIDMode = System.Web.UI.ClientIDMode.Static;
// Add control to placeholder
e.Item.FindControl("commentHolder").Controls.Add(txtComment);
}
}
Get Value On Button Click
Now you need to create the event handler for the button and get the resulting value
protected void btnComment_Click(object sender, EventArgs e)
{
// This is the ID I put in the CommandArgument
Guid id = new Guid(((Button)sender).CommandArgument);
String comment = String.Empty;
// Loop through the repeaterItems to find your control
foreach (RepeaterItem item in rpNotifications.Controls)
{
Control ctl = item.FindControl(
String.Format("txtComment{0}", id.ToString()));
if (ctl != null)
{
comment = ((TextBox)ctl).Text;
break;
}
}
}
Try to get ASP.Net controls using below code
DropDownList drp = (DropDownList)repeated.FindControl("drpdown");
TextBox txt = (TextBox)repeated.FindControl("txt");
CheckBox chk = (CheckBox)repeated.FindControl("chk");
Then you can get values from there respective properties.

how to get checkbox is check in gridview OnRowEditing

if anyone can help me, I have problems with gridview, when I use OnRowEditing and OnRowDeleting and inside asp: TemplateField, ItemTemplate I am using a checkbox, when checked the checkbox in checkbox.checked value is never true,
below is my C # script
<asp: Button ID = "Button1" runat = "server" BackColor = "# EFF1F1" BorderStyle = "None"
onclick = "Button1_Click" Text = "Submit Work Program" />
<asp: GridView ID = "GV_program" runat = "server" AutoGenerateColumns = "False"
Its DataKeyNames = "KD_BIDANG" Width = "100%" AutoGenerateEditButton = "True"
AutoGenerateDeleteButton = "true" OnRowEditing = "GV_program_RowEditing"
OnRowDeleting = "GV_program_RowDeleting" OnRowDataBound = "GV_kegiatan_RowDataBound"
BackColor = "White" EmptyDataText = "No Data Activity" AllowPaging = "True">
<EmptyDataRowStyle BackColor="#FF9900" />
<Columns> <asp:TemplateField HeaderStyle-Width="20px"> <ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" /> </ItemTemplate> </asp:TemplateField>
</ Columns> </ asp: GridView>
C #
protected void Button1_Click (object sender, EventArgs e)
{
foreach (GridViewRow row in GV_program.Rows)
{
if (((CheckBox) row.FindControl ("cbSelect")). Checked)
{
// Delete something (never get here)
}
}
}
take it one step at a time until you get it working......
Try this:
/* put this value at the "class level" */
public static readonly int GRID_VIEW_COLUMN_ORDINAL_chkBoxSELECT = 3; /* Your number may be different, its the ordinal column number. A static readonly or const value makes your code more readable IMHO */
/*Then in your method */
if (null != this.GV_program)
{
Control cntl = null;
foreach (GridViewRow gvr in this.GV_program.Rows)
{
cntl = gvr.Cells[GRID_VIEW_COLUMN_ORDINAL_chkBoxSELECT].FindControl("cbSelect");
CheckBox cbIsApproved = cntl as CheckBox;
if (null != cbIsApproved)
{
bool myValue = cbIsApproved.Checked;
}
}
}
I just ran this code, and it worked for me.
protected void imgbutSave_Click(object sender, ImageClickEventArgs e)
{
if (null != this.gvMain)
{
Control cntl = null;
string finalMsg = string.Empty;
int counter = 0;
StringBuilder sb = new StringBuilder();
foreach (GridViewRow gvr in this.gvMain.Rows)
{
counter++;
cntl = gvr.Cells[GRID_VIEW_COLUMN_ORDINAL_chkBoxIsApproved].FindControl("chkBoxIsApproved");
CheckBox cbIsApproved = cntl as CheckBox;
if (null != cbIsApproved)
{
sb.Append(string.Format("Row '{0}' (chkBoxIsApproved.Checked) = '{1}'", counter, cbIsApproved.Checked) + System.Environment.NewLine);
}
}
finalMsg = sb.ToString();
}
}
and my aspx code
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBoxIsApproved" runat="server" Checked='<%#Eval("IsApproved")%>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
My StringBuilder had all of the checkboxes on my page, with the correct .Checked value.

ASP.NET button does not run the related function

I have an UpdatePanel, in it a GridView, and in it a Repeater. There is a button to add comment. This button post backs but id does not run the function code behind. Here is my code
<updatepanel>
<gridview>
<repeater>
<asp:Button ID="kitapVarYorumEkle" runat="server"
CommandArgument='<%#Eval("id") %>'
CommandName='<%# GridView1.Rows.Count.ToString() %>'
Text="Yorum ekle" class="blueButton"
OnClick="kitapVarYorumEkle_Click" />
</repeater>
</gridview>
</updatepanel>
Code inside the js is:
protected void kitapVarYorumEkle_Click(object sender, EventArgs e)
{
kitapVarYorum temp = new kitapVarYorum();
if (Session["id"] != null)
{
temp.uyeId = Convert.ToInt32(Session["id"]);
}
Button btn = (Button)sender;
temp.kitapVarId = Convert.ToInt32(btn.CommandArgument);
string text = "";
GridViewRow row = GridView1.Rows[Convert.ToInt32(btn.CommandName)];
if (row != null)
{
TextBox txt = row.FindControl("txtYorum") as TextBox;
if (txt != null)
{
text = txt.Text;
}
}
temp.icerik = text;
var db = Tools.DBBaglanti();
db.kitapVarYorums.InsertOnSubmit(temp);
db.SubmitChanges();
// Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
I have tried it outside the the controls and it works
Have you tried the ItemCommand approach?
<asp:Button
CommandArgument='<%#Eval("id") %>'
CommandName="yourCommandNameOfChoice"
Text="Yorum ekle"
ID="kitapVarYorumEkle"
class="blueButton" runat="server"
OnClick="kitapVarYorumEkle_Click" />
now add an ItemCommand event for your repeater:
protected void yourRepeater_ItemCommand(object source , RepeaterCommandEventArgs e)
{
switch(e.CommandName)
{
case "yourCommandNameOfChoice":
// Your Code Here
break;
}
}

Resources