how to create dynamic Required field Validator - c#

I have generated an array of required field validators using following code:
Panel[] divMain = new Panel[22];
DropDownList[] gender = new DropDownList[22];
TextBox[] txtFirstName = new TextBox[22];
TextBox[] txtMiddleName = new TextBox[22];
TextBox[] txtLastName = new TextBox[22];
TextBox[] txtAge = new TextBox[22];
RequiredFieldValidator[] req = new RequiredFieldValidator[30];
and i am creating some dynamic controls using following code:
for (int i = 0; i < noOfad - 1; i++)
{
HtmlGenericControl p = new HtmlGenericControl("p");
HtmlGenericControl strong = new HtmlGenericControl("strong");
strong.InnerText = "Adult" + Convert.ToString(i + 2);
p.Controls.Add(strong);
divAdultMoreForm.Controls.Add(p);
Panel div = new Panel();
HtmlGenericControl p1 = new HtmlGenericControl("p");
p1.InnerHtml = "<span><strong>Full Name (As per Valid Govt Id Proof valid )</strong></span> <span><strong style=' margin-left: 549px;'>Age(in Years 18 +) </strong></span>";
div.Controls.Add(p1);
HtmlGenericControl p2 = new HtmlGenericControl("p");
gender[i] = new DropDownList();
gender[i].Items.Add(new ListItem("Title", "0"));
gender[i].Items.Add(new ListItem("Mr.", "1"));
gender[i].Items.Add(new ListItem("Mrs.", "2"));
gender[i].Items.Add(new ListItem("Ms.", "3"));
gender[i].CssClass = "txt";
p2.Controls.Add(gender[i]);
txtFirstName[i] = new TextBox();
txtFirstName[i].Attributes.Add("placeholder", "First Name");
txtFirstName[i].CssClass = "txt input";
txtFirstName[i].ID = "txtFirstName" + Convert.ToString(i);
req[i].ControlToValidate = txtFirstName[i].ID;//Object refrence not set to an instance ofo an object
req[i].ForeColor = System.Drawing.Color.Red;
req[i].ErrorMessage = "*";
txtFirstName[i].CssClass = "input txt";
txtMiddleName[i] = new TextBox();
txtMiddleName[i].Attributes.Add("placeholder", "Middle Name");
txtMiddleName[i].CssClass = "txt input";
txtMiddleName[i].CssClass = "input txt";
txtMiddleName[i].ID = "txtMiddleName" + Convert.ToString(i);
txtLastName[i] = new TextBox();
txtLastName[i].Attributes.Add("placeholder", "Last Name");
txtLastName[i].CssClass = "txt input";
txtLastName[i].CssClass = "input txt";
txtLastName[i].ID = "txtLastName" + Convert.ToString(i);
txtAge[i] = new TextBox();
txtAge[i].Attributes.Add("placeholder", "Enter Age");
txtAge[i].CssClass = "txt";
p2.Controls.Add(txtFirstName[i]);
p2.Controls.Add(txtMiddleName[i]);
p2.Controls.Add(txtLastName[i]);
p2.Controls.Add(txtAge[i]);
div.Controls.Add(p2);
divAdultMoreForm.Controls.Add(div);
}
But when i am assigning the control to validate to the validator req[i] then there comes an error Object reference not set to an instance of an object.
Can not understand why this problem is occuring.
Any help to correct my code!
Thanks

This is due to the fact that you forgot to initialize the RequiredFieldValidator array object. This seems to be missing from your code :
req[i] = new RequiredFieldValidator();
After this you can play with its properties.
Hope this clears it.

Related

Parameters not reflect Panel in stimulsoft (C#)

showing parameters panel the report.
I do not want show.
(source: picofile.com)
My Code is:
StiReport sr = new StiReport();
sr.Load(ClsVariable.Address + "ReportCustomerBuy.mrt");
sr.Dictionary.Variables["Ccode"].Value = txtCode.Text;
sr.Dictionary.Variables["Cname"].Value = txtName.Text;
sr.Dictionary.Variables["Ctel"].Value = txtTel.Text;
sr.Dictionary.Variables["Caddress"].Value = txtAddress.Text;
sr.Dictionary.Variables["Cfathername"].Value = txtFatherName.Text;
sr.Dictionary.Variables["Cdate"].Value = txtDate.Text;
sr.Dictionary.Variables["CPay"].Value = lblGivePrice.Text;
sr.Dictionary.Variables["CHesabK"].Value = lblPriceKK.Text;
sr.Dictionary.Variables["CBedehkar"].Value = s;
sr.Show();
Disable the request from user property
sr.Dictionary.Variables["Ccode"].RequestFromUser = false;

Dynamically Create Controls Based Off Data Returned From Query

I am querying access table and with my data that is returned I need to be able to create controls. Now the problem with my code is (I obviously need to learn about loops better than I do) the code executes exactly as it should it does the 1st foreach loop then moves to the 2nd foreach loop. So I have all the labels - then I have all the text boxes. I need it to be a 1 to 1 relationship. So Label Text box. This is my current code that is not producing the desired outcome. Can someone assist me in tweaking this to produce the desired outcome of a 1 to 1 relationship of label to textbox
System.Collections.Hashtable lookup = new System.Collections.Hashtable();
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + oName);
olecon.Open();
OleDbCommand command = new OleDbCommand("Query Data Goes Here", olecon);
OleDbCommand command1 = new OleDbCommand("Query Data Goes Here", olecon);
dr = command.ExecuteReader();
while (dr.Read())
{
labelNames.Add(dr[0].ToString());
}
dr.Close();
dr = command1.ExecuteReader();
while (dr.Read())
{
textboxNames.Add(dr[0].ToString());
}
dr.Close();
foreach (string label in labelNames)
{
Label lbl = new Label();
lbl.Name = "lbl_" + index;
lbl.Text = label;
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
index++;
}
foreach (string textbox in textboxNames)
{
TextBox tbx = new TextBox();
tbx.Name = "txt_" + counter;
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
counter++;
}
I don't see any use of textboxNames collection. What you need is, group the two foreach and create label and textbox together and add them to your Form like below
foreach (string label in labelNames)
{
Label lbl = new Label();
lbl.Name = "lbl_" + index;
lbl.Text = label;
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
TextBox tbx = new TextBox();
tbx.Name = "txt_" + index;
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
index++;
}
Rather than doing them as 2 separate foreach loops you could do it in a single for loop, e.g. (assuming labelNames and textboxNames are List<string>):
for (int i = 0; i < labelNames.Count; i++)
{
Label lbl = new Label();
lbl.Name = "lbl_" + labelNames[i];
lbl.Text = labelNames[i];
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
TextBox tbx = new TextBox();
tbx.Name = "txt_" + textboxNames[i];
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
}
Might also be worth checking there are equal numbers of each first as a sanity check:
if (labelNames.Count != textboxNames.Count)
{
//throw exception etc.
}
Replace your two foreach loops with a single for loop that iterates through both lists at the same time.:
for(int i = 0; i < Math.Min(labelNames.Length, textboxNames.Length); i++)
{
Label lbl = new Label();
lbl.Name = "lbl_" + i;
lbl.Text = textboxNames[i];
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
TextBox tbx = new TextBox();
tbx.Name = "txt_" + i;
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
}
The "Math.Min(labelNames.Length, textboxNames.Length)" comparator will make sure the loop stops after whichever list has the fewest entries. I didn't see either of your labelNames or textboxNames collections defined so I'm not sure whether they're arrays or lists or what, so you may need to change "Length" to "Count".

how to add textboxes dynamically to a table row in C#

i want to add textboxes dynamically in C# on a button click in a table row. for that i have used the following code.
[1]: http://pastie.org/7702237.
the problem is i am able to adding as many textboxes as I want but they are adding at same location, i mean the table row is not incrementing for every button click instead it is simply replacing the old table row with the new one. Please help me in how to solve this problem.
Thanks in advance
Ganesh
Web-based applications do not maintain state; to this end the state of the table and any variables is not being maintained. With each postback (generated by the button), the table's state reverts to what it was prior to adding a row and then a row is programatically added to it.
In order to achieve your goal, you will need to maintain state somehow. In the following code snippet I am making use of a session:
private List<TableRow> TableRows
{
get
{
if(Session["TableRows"] == null)
Session["TableRows"] = new List<TableRow>();
return (List<TableRow>)Session["TableRows"];
}
}
The following is your code modified to work with the session variable:
TextBox txtE, txtM, txtB;
Button btnAdd, btnDel;
TableRow trow;
TableCell tcell;
foreach(TableRow tr in TableRows)
tblEduDetails.Controls.Add(tr);
int count = TableRows.Count + 1;
txtE = new TextBox();
txtE.ID = "E" + count.ToString();
txtE.Visible = true;
txtE.Text = "E " + count.ToString();
txtE.BorderWidth = 2;
txtE.TextMode = TextBoxMode.SingleLine;
txtE.Height = 30;
txtM = new TextBox();
txtM.ID = "M" + count.ToString();
txtM.Visible = true;
txtM.Text = "M " + count.ToString();
txtM.TextMode = TextBoxMode.SingleLine;
txtM.Height = 30;
txtB = new TextBox();
txtB.ID = "E" + count.ToString();
txtB.Visible = true;
txtB.Text = "B " + count.ToString();
txtB.TextMode = TextBoxMode.SingleLine;
txtB.Height = 30;
btnAdd = new Button();
btnAdd.ID = "A" + count.ToString();
btnDel = new Button();
btnDel.ID = "D" + count.ToString();
trow = new TableRow();
trow.ID = "R" + count.ToString();
trow.BorderWidth = 1;
tcell = new TableCell();
tcell.ID = "E" + count.ToString();
tcell.Controls.Add(txtE);
trow.Controls.Add(tcell);
tcell = new TableCell();
tcell.ID = "B" + count.ToString();
tcell.Controls.Add(txtM);
trow.Controls.Add(tcell);
tcell = new TableCell();
tcell.ID = "M" + count.ToString();
tcell.Controls.Add(txtB);
trow.Controls.Add(tcell);
tblEduDetails.Controls.Add(trow);
TableRows.Add(trow);

How to set dynamically textbox required

I was created dynamically text boxes. So it must field by user.
So i want to add something like "RequiredFieldValidator". But I dont know how to add dynamically .User can't go to next step without filling these dynamically text boxes. So how can I control this?
this is my code
for (int i = count; i < no; i++)
{
Label lb = new Label();
lb.ID = "lbFname" + NumberOfControls;
lb.Text = "First Name :";
TextBox tbx = new TextBox();
tbx.ID = "Fname" + NumberOfControls;
AdultsListPlaceholder.Controls.Add(lb);
AdultsListPlaceholder.Controls.Add(tbx);
NumberOfControls++;
AdultsListPlaceholder.Controls.Add(new LiteralControl("<br />"));
AdultsListPlaceholder.Controls.Add(new LiteralControl("<br />"));
}
any idea?
Try something like this..
RequiredFieldValidator req = new RequiredFieldValidator();
req.ID = "Req" + NumberOfControls;;
req.ControlToValidate = "Fname" + NumberOfControls;;
req.ErrorMessage = "Name Required";
reqfldVal.SetFocusOnError = true;
AdultsListPlaceholder.Controls.Add(req);

Add textbox via dynamic imagebutton in a panel

I have a problem I seem to stumble over all the time, I have a Drop Down box and you can select a number which creates x number of textboxes with images buttons its for a survey it the image buttons are used to create "Sub-Answers" so they can have answers to answers so my question is I need to when they hit the image button to create a textbox under the orginal textbox here is the code.
for (Int32 i = 1; i <= NumberOfAnwsers; i++)
{
Literal l1 = new Literal();
l1.Text = "<tr><td>Answer " + i + " text.</td><td>";
TextBox tb = new TextBox();
tb.ID = "TextBoxAnswer" + i;
tb.EnableViewState = false;
tb.Width = 300;
Literal l3 = new Literal();
l3.Text = "</td><td>";
Literal l2 = new Literal();
l2.Text = "</td></tr>";
RadColorPicker CPI = new RadColorPicker();
CPI.PaletteModes = PaletteModes.WebPalette;
CPI.ID = "RadColorPicker" + i;
CPI.ShowIcon = true;
CPI.SelectedColor = System.Drawing.Color.Black;
ImageButton IBVideo = new ImageButton();
IBVideo.ID = "IBVideo" + i;
IBVideo.ImageUrl = "/images/video-icon.jpg";
IBVideo.ToolTip = "Add Video";
IBVideo.Height = 20;
IBVideo.Width = 20;
ImageButton IBAdd = new ImageButton();
IBAdd.ID = "IBAdd" + i;
IBAdd.ImageUrl = "/images/add-icon.png";
IBAdd.ToolTip = "Add Sub-Answers";
//IBAdd.OnClientClick = "showDialog(" + i + ");return false;";
IBAdd.Height = 20;
IBAdd.Width = 20;
//Add Textbox
PanelAnswersToQuestions.Controls.Add(l1);
PanelAnswersToQuestions.Controls.Add(tb);
PanelAnswersToQuestions.Controls.Add(l3);
PanelAnswersToQuestions.Controls.Add(CPI);
PanelAnswersToQuestions.Controls.Add(IBVideo);
PanelAnswersToQuestions.Controls.Add(IBAdd);
PanelAnswersToQuestions.Controls.Add(l2);
}
As you can see I just add controls to the panel, I need to know when that ImageBUtton is hit I can add a Textbox and in this case it could be more then just one textbox to it.
I hope this is clear but for some reason I dont think it is ... sorry.
I have added a radwindow and poping that up sending the Data to the partent via javascript the which created a new problem for me, I can not in javascript seem to find the dynamicly created hiddenfield
function OnClientClose(radWindow) {
var oWnd = $find("<%=RadWindowAddSubAnswer.ClientID%>");
var SubAnswerValues = oWnd.get_contentFrame().contentWindow.document.forms(0).HiddenFieldSubAnswers.value;
alert(SubAnswerValues);
var AnswerID = oWnd.get_contentFrame().contentWindow.document.forms(0).HiddenFieldAnswerID.value;
alert(AnswerID);
var HiddenName = "HiddenFieldSubAnswers" + AnswerID;
alert(HiddenName);
document.getElementById(HiddenName).value = SubAnswerValues;
$get("DivSubAnswers" + AnswerID).innerHTML = SubAnswerValues;
}
The "document.getElementById(HiddenName).value = SubAnswerValues;" seems to never be found, I also tried $get(HiddenName).value = SubAnswerValues; that does not seem to work either both come back as null as for the code behind its:
HiddenField HFSubAnswers = new HiddenField();
HFSubAnswers.ID = "HiddenFieldSubAnswers" + i;
HFSubAnswers.Value = "0";
Im not sure if I got your question right but if you need to dynamically add controls on a Page here is what I can say.
Before adding your control I guess you need to find the control where you need to add it on, Add the control then assign the properties.
PlaceHolder myPlaceHolder = (PlaceHolder)Page.FindControl("PlaceHolder1");
myPlaceHolder.Controls.Add(myButton);
myButton.Text = "Hello World";
For a more detailed expalnation go here http://anyrest.wordpress.com/2010/04/06/dynamically-removing-controls-in-a-parent-page-from-a-child-control/

Categories

Resources