Set text from code behind - c#

I have set the label text as empty as it depend on the situation.
In ascx file I set as below code:
<td runat="server" id="tdAvailableD" class="text-center" style ="font-size: 12px">
<asp:Label ID="lblAvailable" runat="server" ForeColor="Red" Visible="true" Text=""></asp:Label></td>
In ascx.cs file I set as below code:
private void CheckQuantityError()
{
for (int i = 0; i < dlDiscountedProducts.Items.Count; i++)
{
{
DropDownList qty = (DropDownList)dlDiscountedProducts.Items[i].FindControl("ddlQuantity");
HiddenField productId = (HiddenField)dlDiscountedProducts.Items[i].FindControl("hdnProductID");
HiddenField discountRuleId = (HiddenField)dlDiscountedProducts.Items[i].FindControl("hdnDiscountRuleId");
//HiddenField AvailStatus = (HiddenField)dlDiscountedProducts.Items[i].FindControl("hdnAvailStatus");
//HtmlGenericControl spanAvailStatus = (HtmlGenericControl)dlDiscountedProducts.Items[i].FindControl("spanAvailStatus");
Label lblOutofStockError = (Label)dlDiscountedProducts.Items[i].FindControl("lblOutofStockError");
Label lblAvailable = (Label)dlDiscountedProducts.Items[i].FindControl("lblAvailable");
DCShoppingCartItem shoppingCartItem = new DCShoppingCartItem();
if (null != Product)
{
bool status = false;
try
{
using (new AcsServiceContextScope())
{
status = AcsServiceContextScope.Current.Products.GetAxStockAvailability(new GetStockAvailabilityRequest()
{
ModelNumber = Product.ModelNumber,
Quantity = 1,
ProductId = Product.Id
}).StockStatus;
}
}
catch (Exception ex)
{
Logging.EventLogger.LogEvent(ex);
}
if (status == true)
{
//spanAvailStatus.Attributes["class"] = "glyphicon glyphicon-remove";//available
lblAvailable.Visible = true;
lblAvailable.Text = "In Stock";
lblOutofStockError.Visible = true;
lblAlert.Visible = true;
}
else
{
//spanAvailStatus.Attributes["class"] = "glyphicon glyphicon-ok";//not available
lblAvailable.Visible = true;
lblAvailable.Text = "No Stock";
lblOutofStockError.Visible = true;
lblAlert.Visible = true;
//qty.BackColor = System.Drawing.Color.Yellow;
}
}
}
}
}
but the text not display in page.The function should show, if the item have quantity then it will show in stock.

Try keeping lblAvailable inside an update panel and try posting back the page.
The reason could be setting the text in label is not posted back to the page.

Check if the value is Coming to the lblAvailable properly.
If it is? then put the
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<td runat="server" id="tdAvailableD" class="text-center" style ="font-size: 12px">
<asp:Label ID="lblAvailable" runat="server" ForeColor="Red" Visible="true" Text=""></asp:Label></td>
</ContentTemplate>
</asp:UpdatePanel>
then in .cs use this
UpdatePanel.Update();
and remove Text and ForeColor properties rather do it from .cs
u can even give different colors
lblAvailable.ForeColor = System.Drawing.Color.Green;//or red when not in stock

Related

How to prevent page to scroll to top after gridview checkbox changed

enter image description herei tried many solutions before to prevent page scroll top after checkbox in grid view was changed but no one solve my problem .. please help!
thanks in advance
(update)-->
this is the Design code:
<asp:Panel ID="Panel2" runat="server" CssClass="Panel" GroupingText="<img src='Images/lightbulb.gif' /> Step 2: Seclect Threats to detect">
<%--<h1 style="text-align:right;padding-right:30px;position:absolute;right:40px;top:300px" > <asp:Label ID="lbl_cost" runat="server" Text="0 $" ></asp:Label></h1>--%>
<ajax:TabContainer ID="tc_thread_types" runat="server" AutoPostBack="true" Width="100%" CssClass="Tab" ActiveTabIndex="0">
<ajax:TabPanel ID="tab_mem_threads" runat="server" HeaderText="Member Threats" CssClass="Tab">
<ContentTemplate>
<div id="scrollDiv1" style="width: 100%; max-height: 400px; overflow: auto" >
<asp:GridView ID="gv_ThDetails_Mem" runat="server" CssClass="Grid"
Style="width: 100%; padding: 25px; margin-top: 10px; margin-bottom: 10px"
AutoGenerateColumns="False" OnRowDataBound="gv_ThDetails_mem_RowDataBound">
<Columns>
<asp:BoundField DataField="thread_id" HeaderText="Threat Id" />
<asp:BoundField DataField="thread_desc" HeaderText="Threat Description" />
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="ch_all_mem" runat="server" AutoPostBack="true" OnCheckedChanged="ch_all_mem_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<%--<asp:CheckBox ID="cb_includedThreat_mem1" Onclick='<%# "ShowCurrentTime(" +Eval("serial") + " );" %>' runat="server" />--%>
<asp:CheckBox ID="cb_includedThreat_mem" runat="server" AutoPostBack="true" OnCheckedChanged="cb_includedThreat_mem_CheckedChanged" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="serial" HeaderText="serial" Visible="false" />
</Columns>
</asp:GridView>
</div>
<script type="text/javascript">
//var prm = Sys.WebForms.PageRequestManager.getInstance();
//prm.add_beginRequest(beginRequest);
//function beginRequest() {
// prm._scrollPosition = null;
//}
</script>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
And this is the code behind:
protected void cb_includedThreat_mem_CheckedChanged(object sender, EventArgs e)
{
try
{
//up_frdSetup.Update();
CheckBox included = (CheckBox)sender;
//GridViewRow gr = (GridViewRow)included.Parent.Parent;
int count;
if (rbl_memType.SelectedIndex == -1)
{
included.Checked = false;
SystemMsg.fn_SetMessageProperties("U6", "You should select membership first!"); // casting
SystemMsg.Focus();
return;
}
if (Session["IsExpired"] != null && Session["IsExpired"].ToString().Equals("Y") && rbl_memType.SelectedValue.ToString().Equals("T"))
{
included.Checked = false;
ib_save.Enabled = false;
// ib_save.CssClass = "btn disabled";
ib_save.ToolTip = "Submit was disabled As your trial version was expired!";
SystemMsg.fn_SetMessageProperties("U6", "Your trial version was expired! Please select Preimuim Subscription Now!");
//lbl_cln_msg.Text = "Your trial version was expired! Please select Premium Subscription Now!";
//cln_msg.Style.Add("display", "normal");
return;
}
if (ViewState["cnt_th_mem"] == null)
{
count = 0;
}
else
{
count = int.Parse(ViewState["cnt_th_mem"].ToString());
}
if (included.Checked)
{
count++;
ViewState["cnt_th_mem"] = count;
}
else if (!included.Checked && count > 0)
{
count--;
ViewState["cnt_th_mem"] = count;
}
included.Focus();
if (rbl_memType.SelectedValue.ToString().Equals("T"))
{
int tot_cnt = fn_check_tot_checked_threads();
if (tot_cnt > 3)
{
included.Checked = false;
count--;
ViewState["cnt_th_mem"] = count;
//lbl_cln_msg.Text = "The Maximum allowed threats in trial membership is Three only!";
//cln_msg.Style.Add("display", "normal");
SystemMsg.fn_SetMessageProperties("U6", "The Maximum allowed threats in trial membership is Three only!");
SystemMsg.Focus();
return;
}
//lbl_cost.Text = "0$";
//ViewState["cnt_th_mem"] = 0;
}
else if (rbl_memType.SelectedValue.ToString().Equals("P"))
{
//lbl_cost.Text = (Double.Parse(Session["th_price"].ToString()) * count) + "$";
ViewState["cnt_th_mem"] = count;
}
//fn_checkIncluded_Mem_Threads();
CheckBox ch_all = gv_ThDetails_Mem.HeaderRow.FindControl("ch_all_mem") as CheckBox;
if (count == gv_ThDetails_Mem.Rows.Count)
{
ch_all.Checked = true;
}
else if (count == 0)
{
ch_all.Checked = false;
}
else
{
ch_all.Checked = false;
}
fn_check_tot_cost();
}
catch (System.IO.IOException eio)
{
SystemMsg.fn_SetMessageProperties("S1", eio.Message); // IO
SystemMsg.Focus();
return;
}
catch (NullReferenceException ex)
{
SystemMsg.fn_SetMessageProperties("S2", ex.Message); // NULL
SystemMsg.Focus();
return;
}
catch (SqlException sqlEx)
{
SystemMsg.fn_SetMessageProperties("S4", sqlEx.Message); // SQL
SystemMsg.Focus();
return;
}
catch (Exception exe)
{
SystemMsg.fn_SetMessageProperties("S0", exe.Message);
SystemMsg.Focus();
return;
}
}
thanks in advance ..
Put this in the page directive <%# Page %>
MaintainScrollPositionOnPostback = "true"
It happens due to page PostBack. The above ensures the position of the scroll after page PostBack.
Or keep the GridView in a div and use JavaScript trick to do so: Maintain Scroll Position in Div

ViewState won't hold dynamically created controls' value, even though I preserve the same ids in postbacks

I am trying to create a simple form generating webpage that user can select different controls via a DropDownList, add a Text property to it(and a GroupName property if ii was a RadioButton) and then click a button to generate that control right in the page for previewing purpose (I am also going to add another button to insert the form's information in a database but this is not my problem right now)
this is my aspx page:
<div class="main-wrapper">
<form dir="rtl" id="form" runat="server">
<label>Desired Control : </label>
<asp:DropDownList AutoPostBack="true" ID="ddlControlType" OnSelectedIndexChanged="ddlControlType_SelectedIndexChanged" runat="server">
<asp:ListItem Text="label"></asp:ListItem>
<asp:ListItem Text="text box"></asp:ListItem>
<asp:ListItem Text="check box"></asp:ListItem>
<asp:ListItem Text="radio button"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<label class="label">control's text : </label>
<asp:TextBox ID="txtboxText" runat="server" CssClass="txtbox"></asp:TextBox>
<label class="label">group name (only for radio button)</label>
<asp:TextBox Enabled="false" ID="txtboxGroupName" runat="server" CssClass="txtbox"></asp:TextBox>
<br /><br />
<asp:Button ID="btnAddControl" CssClass="btn" Text="add to form" OnClick="btnAddControl_Click" runat="server" />
<hr />
<h1>form preview</h1>
<asp:Panel ID="panel" runat="server">
</asp:Panel>
</form>
this is the code behind:
public Dictionary<string, Type> ControlTypes
{
get { return (Dictionary<string, Type>)Session["ControlTypes"]; }
set { Session["ControlTypes"] = value; }
}
public int NumberOfControls
{
get { return (int)ViewState["NumOfControls"]; }
set { ViewState["NumOfControls"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.NumberOfControls = 0;
ControlTypes = new Dictionary<string, Type>();
}
else
this.CreateControls();
}
private void CreateControls()
{
for (int counter = 0; counter < this.NumberOfControls; counter++)
{
string controlId = "control_id_" + counter.ToString();
Type controlType = ControlTypes[controlId];
PropertyInfo[] properties = controlType.GetProperties();
object controlObject = Activator.CreateInstance(controlType);
foreach (var property in properties)
{
if (property.Name == "ID")
property.SetValue(controlObject, controlId, null);
}
panel.Controls.Add(controlObject as Control);
}
}
protected void ddlControlType_SelectedIndexChanged(object sender, EventArgs e)
{
switch (ddlControlType.SelectedIndex)
{
case 0:
case 2:
txtboxText.Enabled = true;
txtboxGroupName.Enabled = false;
break;
case 1:
txtboxText.Enabled = false;
txtboxGroupName.Enabled = false;
break;
case 3:
txtboxText.Enabled = true;
txtboxGroupName.Enabled = true;
break;
}
}
protected void btnAddControl_Click(object sender, EventArgs e)
{
Control tempControl = null;
switch (ddlControlType.SelectedIndex)
{
case 0:
tempControl = new Label();
((Label)tempControl).Text = txtboxText.Text;
break;
case 1:
tempControl = new TextBox();
break;
case 2:
tempControl = new CheckBox();
((CheckBox)tempControl).Text = txtboxText.Text;
break;
case 3:
tempControl = new RadioButton();
((RadioButton)tempControl).Text = txtboxText.Text;
((RadioButton)tempControl).GroupName = txtboxGroupName.Text;
break;
}
string controlId = "control_id_" + this.NumberOfControls.ToString();
tempControl.ID = controlId;
panel.Controls.Add(tempControl);
this.NumberOfControls++;
ControlTypes.Add(controlId, tempControl.GetType());
}
as you can see, I preserve the id's of the controls, but the viewstate won't update their values.the controls will be added to the form with the desired id, but its values won't be set at all
what should I do?

append tr when a value is not null using item template

I am appending rows using item template
<tr>
<td>
<asp:HyperLink ID="HyperLink1" NavigateUrl="bla" CssClass="display:inherit !important;" Text='<%# someFunction(School.Name,"Name") %>' runat="server" />
</td>
</tr>
the problem with the above one is if someFunction(School.Name,"Name") returns null it appends empty tr, so i want to append tr only if someFunction(School.Name,"Name")!=null
So i tried the below code by adding a if condition but it is not compiling !!
It says school.name is not defined
<% if(someFunction(School.Name,"Name")!=null){
<tr>
<td>
<asp:HyperLink ID="HyperLink1" NavigateUrl="bla" CssClass="display:inherit !important;" Text='<%# someFunction(School.Name,"Name") %>' runat="server" />
</td>
</tr>
} %>
You could take care of it from the code behind.
<td id="tdAppend" runat="server"> Content </td>
if(School.Name == null)
tdAppend.Visible = false;
UPDATED ANSWER:
currentItemIndex = -1;
listView.ItemDataBound += listView_ItemDataBound;
CheckQueryString();
//Hide or show the table header based on id
HtmlControl thControl = listView.FindControl("thAppend") as HtmlControl;
if (thControl != null)
{
if (obj.ID == 12)
{
thControl.Visible = true;
}
else
{
thControl.Visible = false;
for (int i = 0; i < listView.Items.Count; i++)
{
HtmlControl tdControl = listView.Items[i].FindControl("tdSchoolName") as HtmlControl;
if (tdControl != null)
{
tdControl.Visible = false;
}
}
}
}
For convenience:
void listView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
currentItemIndex++;
ListViewDataItem dataitem = (ListViewDataItem)e.Item;
HtmlTableRow trControl = (HtmlTableRow)e.Item.FindControl("MainTableRow");
if (IsOdd(currentItemIndex))
trControl.BgColor = "DarkGray";
}
}
private bool IsOdd(int value)
{
return value % 2 != 0;
}
It's a pretty straight forward practice.. Handling the ListView.OnItemDataBinding event.
Markup
<%# Import Namespace="MyNamespace" %>
<asp:ListView ID="lview" runat="server" OnItemDataBound="lview_ItemDataBound" ItemPlaceholderID="Placeholder1">
<ItemTemplate>
<tr>
<td><%# ((School)Container.DataItem).Name %></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table>
<div id="Placeholder1" runat="server"></div>
</table>
</LayoutTemplate>
</asp:ListView>
Code-Behind
namespace MyNamespace
{
public class Default : Page
{
IEnumerable<School> dataItems {get;set;}
protected void Page_Load(object sender, EventArgs e)
{
dataItems = new School[] { new School() { Name = "School 1" }, new School() { Name = "School 2" }, new School() { Name = null }, new School() { Name = "School 3" } }.AsEnumerable();
lview.DataSource = dataItems;
lview.DataBind();
}
protected void lview_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListView listview = (ListView)sender;
ListViewItem row = e.Item;
School dataItem = (School)e.Item.DataItem;
if (dataItem.Name == null)
{
row.Visible = false;
}
}
}
public class School
{
public string Name { get; set; }
}
}
personally, I don't usually use tables.. it's a fairly odd-looking layout template.

code behind field validation only if value is selected in dropdown list

I'm not an asp.net guru, so I'm facing bad times with this silly matter.
I have a registration form where a field (VAT NUMBER called 'piva') must be validate only if from a dropdown list the value "IT" has been selected.
This is the front code:
<asp:TextBox ID="pivaTextBox" runat="server" Text='<%# Bind("piva") %>'
MaxLength="50" Width="400px" />
<asp:RequiredFieldValidator ID="RequiredPiva" runat="server"
ControlToValidate="pivaTextBox"
ErrorMessage="<%$ Resources:Resource, CampoObbligatorio %>" Display="Dynamic"
CssClass="little_text" />
<asp:CustomValidator ID="PivaEsistente" runat="server"
ErrorMessage="Partita IVA esistente nel database" meta:resourcekey="PivaEsistente"
ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic"
onservervalidate="PIVAEsistente_ServerValidate"></asp:CustomValidator>
<asp:RegularExpressionValidator ID="PivaSize" runat="server" ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic" ErrorMessage="Check the VAT Number length. 11 characters and only numbers." ValidationExpression="[0-9]{11}" ValidationGroup="pivaItalia">
</asp:RegularExpressionValidator>
In the code behind I wrote this:
protected void PIVAEsistente_ServerValidate(object source, ServerValidateEventArgs args)
{
string piva = args.Value;
using (CMALinqModelDataContext ent = new CMALinqModelDataContext())
{
var n = (from u in ent.VUser
where u.piva == piva
select u).Count<VUser>();
args.IsValid = n.ToString().Equals("0");
}
}
protected void nazioneDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
DropDownList ddlProv = (DropDownList)FormUser.FindControl("provinciaDropDownList");
if ("it".Equals(ddl.SelectedValue))
{
ddlProv.Enabled = true;
Page.Validate("pivaItalia");
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
}
}
the first method checks if a VAT number already exists and it works.
The second one check if "it" has been selected from the nations dropdown list and unlock the provinces dropdownlist AND SHOULD validate the VAT number according the RegularExpressionValidator above.
The fact is that it is always validate, but worst even if I get the error message, the form can be submitted.
That's not good.
Anyone could suggest any solution? What am I missing?
Beside capital letters that you have to sort out, if it is the case, the problem is the "SelectedValue" you shall use "SelectetItem".
if (ddl.SelectedItem.Equals("it"))
{
ddlProv.Enabled = true;
Page.Validate("pivaItalia");
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
}
I tested with this on a comboBox(ddl) where I have: it, pippo, papa, etc.., and it works:
private void button1_Click(object sender, EventArgs e)
{
if (ddl.SelectedItem.Equals("it"))
{
label1.Text = "ok";
}
else
{
label1.Text = "no";
}
}
So if you still have problems, please explain better what is happening, may be the problem is now somewhere else.
Looks like your problem is casing.
In your question you state " I have a registration form where a field (VAT NUMBER called 'piva') must be validate only if from a dropdown list the value "IT" has been selected.", yet in your code you are comparing the lowercase value to the selected value in this code:
if ("it".Equals(ddl.SelectedValue))
{
ddlProv.Enabled = true;
Page.Validate("pivaItalia");
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
}
Instead force the values being compared to the same case (either .ToLower() or .ToUpper()), like this:
if ("it".Equals(ddl.SelectedValue.ToLower()))
{
ddlProv.Enabled = true;
Page.Validate("pivaItalia");
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
}
OR
if ("IT".Equals(ddl.SelectedValue.ToUpper()))
{
ddlProv.Enabled = true;
Page.Validate("pivaItalia");
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
}

Add ValidationControls dynamically to updatepanel? [ASP.NET]

I have a problem with my dynamic updatepanel that I've created.
The problem is that i want to add a validator,i.e RequriedFieldValidator, to every element that i'm creating on the serverside.
This above works fine.
But when i'm clicking the submit button it does nothing. I can see in the htmlShellcode that a span element is there showing the error, but it has the "style="visibility=hidden".
How do i solve this issue? i'm not really sure i'm doing it right from the beginning either(very new to programming).
MARKUP:
<asp:Panel ID="UpdatepanelWrapper" CssClass="Updatepanelwrapper" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="WholeWrapper">
<asp:PlaceHolder runat="server" ID="QuestionWrapper">
<asp:PlaceHolder runat="server" ID="LabelQuestion"><asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="Question"></asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnDelete" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Panel ID="ButtonPanel" CssClass="ButtonPanel" runat="server">
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/Images/Deleteicon.png" CssClass="DeleteButton" OnClientClick="btnDelete_Click" />
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/Addicon.png" CssClass="AddButton" OnClientClick="btnAddQuestion_Click" />
</asp:Panel>
</asp:Panel>
SERVERSIDE CODE: (Override method OnInit is the important one)
public partial class _Default : Page
{
static int CountOfQuestions = 1;
private RequiredFieldValidator[] ArrRequiredFieldQuestion;
private Panel[] ArrWholePanel;
private Panel[] ArrQuestionPanel;
private Label[] ArrQuestionLabel;
private TextBox[] ArrQuestionBox;
protected void Page_Load(object sender, EventArgs e)
{
}
private void LoadControls()
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAdd") //Ändra till btnAddQuestion om en "button" ska användas
{
CountOfQuestions++;
}
if (myControl.ID.ToString() == "btnDelete")
{
CountOfQuestions--;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!IsPostBack)
{
CountOfQuestions = 1;
}
LoadControls();
ArrRequiredFieldQuestion = new RequiredFieldValidator[CountOfQuestions];
ArrWholePanel = new Panel[CountOfQuestions];
ArrQuestionPanel = new Panel[CountOfQuestions];
ArrQuestionLabel = new Label[CountOfQuestions];
ArrQuestionBox = new TextBox[CountOfQuestions];
for (int i = 0; i < CountOfQuestions; i++)
{
RequiredFieldValidator ReqFieldQuestion = new RequiredFieldValidator();
PlaceHolder WholeWrapper = UpdatePanel1.FindControl("WholeWrapper") as PlaceHolder;
Panel WholePanel = new Panel();
Panel QuestionPanel = new Panel();
Panel CorrectAnswerPanel = new Panel();
Label QuestionLabel = new Label();
TextBox Question = new TextBox();
QuestionLabel.Text = "Write your question";
Question.TextMode = TextBoxMode.MultiLine;
Question.Width = 550;
Question.Height = 50;
WholePanel.ID = "WholePanel" + i.ToString();
QuestionPanel.ID = "QuestionPanel" + i.ToString();
Question.ID = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ID = "Validate" + i.ToString();
ReqFieldQuestion.ControlToValidate = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ValidationGroup = "QuestionGroup";
ReqFieldQuestion.ErrorMessage = "Error";
ReqFieldQuestion.Attributes.Add("runat", "server");
QuestionPanel.CssClass = "QuestionEntry";
QuestionPanel.Controls.Add(QuestionLabel);
QuestionPanel.Controls.Add(Question);
QuestionPanel.Controls.Add(ReqFieldQuestion);
WholeWrapper.Controls.Add(WholePanel);
WholePanel.Controls.Add(QuestionPanel);
ArrRequiredFieldQuestion[i] = ReqFieldQuestion;
ArrQuestionPanel[i] = QuestionPanel;
ArrQuestionLabel[i] = QuestionLabel;
ArrQuestionBox[i] = Question;
}
}
protected void btnAddQuestion_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
public static Control GetPostBackControl(Page thePage)
{
Control postbackControlInstance = null;
if (postbackControlInstance == null)
{
for (int i = 0; i < thePage.Request.Form.Count; i++)
{
if ((thePage.Request.Form.Keys[i].EndsWith(".x")) || (thePage.Request.Form.Keys[i].EndsWith(".y")))
{
postbackControlInstance = thePage.FindControl(thePage.Request.Form.Keys[i].Substring(0, thePage.Request.Form.Keys[i].Length - 2));
return postbackControlInstance;
}
}
}
return postbackControlInstance;
}
But when i'm clicking the submit button it does nothing.
Since I don't see a Submit button, I'm taking a guess that you mean the Add and Remove buttons. If this is the case, the problem is that all your RequiredFieldValidators have the ValidationGroup property set to QuestionGroup but this is not set in any of your buttons.
Modify the Buttons like this:
<asp:ImageButton ID="btnAdd" runat="server" ValidationGroup="QuestionGroup" ... />

Categories

Resources