How do I add a variable for the textbox ID inside a function? - asp.net

public partial class _Default : System.Web.UI.Page
{
double[] array = new double[5];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<5;i++)
{
array[i] = Convert.ToDouble(TextBox(i+1).Text);
}
}
}
This is my code, I have 5 textboxes, I'd like to refer to them with the int (i) inside the loop.
array[i] = Convert.ToDouble(TextBox(i+1).Text);
the text boxes are named 'TextBox1' , 'TextBox2', 'TextBox3, etc.
Is it possible in C#?

You could if you use Control.FindControl
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
TextBox currenTextBox = (TextBox) FindControl("TextBox" + i);
if (!string.IsNullOrEmpty(currenTextBox?.Text))
{
if (double.TryParse(currenTextBox.Text, out var result))
{
array[i] = result;
}
}
}
}

Related

In Online Exam,How I Will Show The Next quest and ans After Clicking The Next Button.I Can Show Only The First quest

The code I have so far tried
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Time();
Question();
}
}
public void Question()
{
int res2 = Convert.ToInt32(lblsubject.Text);
var res3 = (from test in obj.Quest where test.subid == res2 select test).FirstOrDefault();
if (res3 != null)
{
lblqst.Text = res3.question;
opt1.Text = res3.answ1;
opt2.Text = res3.answ2;
opt3.Text = res3.answ3;
opt4.Text = res3.answ4;
}
}
protected void btn_next_Click(object sender, EventArgs e)
{
/*what code to use here?this is the next button where after clicking it next question will display*/
}

How to prevent to adding two lists in asp.net?

How to Prevent adding two controls or to lists ? I've tried this code but it doesn't work... Pease help!
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ViewState["check"] = "First_Time";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["check"] == "First_Time")
{
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
ViewState["check"] = "Scond_Time";
}
else
{
Response.Write("Sorry, Can't create a list on second time");
}
}
The problem with your approach is that the button click event is triggered on postback, hence your postback check in Page_Load is pointless.
Since the CheckBoxList.Items are stored in Viewstate by default(it implements IStateManager), why don't you simply check if the items are already added?
protected void Button1_Click(object sender, EventArgs e)
{
if (CheckBoxList1.Items.Count < 6)
{
CheckBoxList1.Items.Clear();
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
}
else
{
// don't use Response.Write to output messages but controls
Response.Write("Sorry, Can't create a list on second time");
}
}

Listview change applies after 2nd postback?

i have a listview and a button out of this list view, on button click i want to add a "insert" row defined in InsertItemTemplate. The problem is when i click the button, this row is added(i know this because when a do any postback aftewards this row really shows), but isnt shown/rendered. So the question is: why this change doesn´t apply on the first postback - button click? here is my code:
EDIT:
Whole Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem ByName = new ListItem("By name", "Name");
ListItem ByPhone = new ListItem("By phone", "Phone");
ListItem ByEmail = new ListItem("By email", "Email");
FilterTypeDDL.Items.Add(ByName);
FilterTypeDDL.Items.Add(ByPhone);
FilterTypeDDL.Items.Add(ByEmail);
FilterTypeDDL.DataBind();
}
}
//protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)
//{
//switch (e.CommandName)
//{
//case "EditItem":
// break;
//case "InsertItem":
// if (Page.IsValid)
// {
// string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
// string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
// string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
// DAORestaurant.InsertRestaurant(NameTxt, PhoneTxt, EmailTxt);
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
// }
// break;
//case "CancelCreation":
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
//case "Articles":
// Session["Restaurant"] = e.CommandArgument.ToString();
// Control ArticlesCtrl = LoadControl("~/Controls/Article.ascx");
// ListViewItem Item = (ListViewItem)e.Item;
// Item.FindControl("CtrlPlaceHolder").Controls.Add(ArticlesCtrl);
//}
//}
protected void closeButton_Click(object sender, EventArgs e)
{
}
protected void newArticleButton_Click(object sender, EventArgs e)
{
}
protected void NewRestaurantBtn_Click(object sender, EventArgs e)
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
//SetDataSource();
//ListView.DataBind();
}
protected void ValidateName(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = (NameTxt.Length > 2 && NameTxt.Length < 51);
}
protected void ValidateUniqueness(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = DAORestaurant.IsUnique(NameTxt);
}
protected void ValidatePhone(object source, ServerValidateEventArgs args)
{
string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
Regex regex = new Regex(#"^\d{3}\s\d{3}\s\d{3}$");
args.IsValid = regex.IsMatch(PhoneTxt);
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
args.IsValid = regex.IsMatch(EmailTxt);
}
protected void ShowAllBtn_Click(object sender, EventArgs e)
{
Session["ALL"] = true;
ListView.DataSource = DAORestaurant.GetRestaurants();
ListView.DataBind();
}
protected void FilterBtn_Click(object sender, EventArgs e)
{
string filterType = FilterTypeDDL.SelectedValue;
string substring = StringTB.Text.Trim().ToUpper();
Session["ALL"] = false;
Session["FilterType"] = filterType;
Session["Substring"] = substring;
ListView.DataSource = DAORestaurant.GetRestaurants(substring, filterType);
ListView.DataBind();
}
protected void ListView_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView.EditIndex = e.NewEditIndex;
//SetDataSource();
//ListView.DataBind();
}
protected void ListView_ItemInserting(object sender, ListViewInsertEventArgs e)
{
}
protected void ListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
if (e.CancelMode == ListViewCancelMode.CancelingInsert)
{
ListView.InsertItemPosition = InsertItemPosition.None;
}
else
{
ListView.EditIndex = -1;
}
//SetDataSource();
//ListView.DataBind();
}
private void SetDataSource()
{
if ((bool)Session["ALL"])
{
ListView.DataSource = DAORestaurant.GetRestaurants();
}
else
{
ListView.DataSource = DAORestaurant.GetRestaurants((string)Session["Substring"], (string)Session["FilterType"]);
}
}
The code commented out is what i used before, i´ve switched to what you can see now, but the problem still persists. Only when i uncomment those 2 commented lines in each event, the changes apply instantly, but i know i cannot use such a method that many times, and it should not even be there.
Because of the order of execution. Try setting it in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack &&
!string.IsNullOrEmpty(Request.Form[NewRestaurantBtn.ClientID]))
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
}
}

How to preserve dynamically created controls?

I want to preserve the dynamically created control when postback occurs .
protected void Page_Load(object sender, EventArgs e)
{
}
private void CreateTable()
{
HtmlTableRow objHtmlTblRow = new HtmlTableRow();
HtmlTableCell objHtmlTableCell = new HtmlTableCell();
objHtmlTableCell.Controls.Add(new TextBox());
objHtmlTblRow.Cells.Add(objHtmlTableCell);
mytable.Rows.Add(objHtmlTblRow);
this.SaveControlState();
// this.Controls.Add(mytable);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTable();
}
It can be achieved by calling CreateTable() in Page_Load. Is there any alternative way to preserve the control
Thanks
You can add them to a List when you create them and save your List to Session. On postback (Page_Load) load them from your Session to your Page.
the below code should work
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateTable()
}
public static Control GetPostBackControl(Page thisPage)
{
Control ctrlPostedback = null;
string ctrlName = thisPage.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
{
ctrlPostedback = thisPage.FindControl(ctrlName);
}
else
{
foreach (string Item in thisPage.Request.Form)
{
Control c = thisPage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
ctrlPostedback = c;
}
}
}
return ctrlPostedback;
}
The code works from UpdatePanel
Reference:http://www.asp.net/ajax/videos/how-to-dynamically-add-controls-to-a-web-page

Problem with page lifecycle

The qustion was modified by me to show a complete picture.
I have a basic question:
code behind:
protected void Page_Load(object sender, EventArgs e)
{
int firstPageIndex = 0;
int lastPageIndex = 5;
if (TotalPageNumber > 5)
{
if ((TotalPageNumber - PageIndex) <= 5)
firstPageIndex = TotalPageNumber - 5;
firstPageIndex = PageIndex < 3 ? 0 : PageIndex - 2;
}
else
{
firstPageIndex = 0;
lastPageIndex = TotalPageNumber;
}
for (int i = firstPageIndex; i < firstPageIndex + lastPageIndex; i++)
{
LinkButton lnk = new LinkButton();
lnk.CommandArgument = i.ToString();
lnk.Click += new EventHandler(lblPageNumber_Click);
lnk.ID = "lnkPage" + (i + 1).ToString();
lnk.Text = (i + 1).ToString();
plcPagerHolder.Controls.Add(lnk);
} }
int _pageIndex;
public int PageIndex
{
get
{
object objPage = ViewState["_pageIndex"];
if (objPage == null)
{
_pageIndex = 0;
}
else
{
_pageIndex = (int)objPage;
}
return _pageIndex;
}
set {ViewState["_pageIndex"] = value; }
}
protected void lnkPagerNext_Click(object sender, EventArgs e)
{
PageIndex = PageIndex == TotalPageNumber - 1 ? 0 : PageIndex + 1;
}
The problem is with Page_Load event, I expect to get new PageIndex after the linkbutton is clicked.
Update:
My Foo adds new controls to the page, based on provide Page index so I guess I can't put it in Prerender.
Two options
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Foo (PageIndex);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
PageIndex = int.Parse(((LinkButton)sender).CommandArgument);
Foo (PageIndex);
}
or
protected void Page_PreRender(object sender, EventArgs e)
{
Foo (PageIndex);
}
you can place Foo (PageIndex) in Page_LoadComplete event instead of Page_Load, i.e.
protected void Page_LoadComplete(object sender, EventArgs e)
{
Foo (PageIndex);
}
LoadComplete event is raised after Control events.
Edit:
LoadComplete is the earliest place where you can safely access new pageindex and also you can add there another controls, but that is possible also in PreRender.
And you will, but Page_Load gets called before the event handler for the linkbutton .. so, you can't really expect it to be changed yet.

Resources