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;
}
}
Related
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;
}
}
}
}
I want to check if btnTest_Click is clicked in another Button6_Click event.Below is my code.....Please help
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if()
}
as per Kevin's answer but instead of:
protected bool testPassed;
Have this:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
By accessing the value of this property via view state the value will persist between requests.
I would declare a class level boolean called testPassed.
Set it to false in the onload event if it is not a Postback.
Set it to true in the btnTest_Click event handler
Edit to add an example:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
testPassed=false;
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
testPassed=true;
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if(testPassed)
}
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*/
}
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
I had login Page and it worked well but remember me check box didn't work well and I couldn't know where the error please anyone help me this is my code
public partial class _Default : System.Web.UI.Page
{
public TextBox Usertxt,Passwordtxt;
protected void Page_Load(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
if (!IsPostBack)
{
if (Request.Cookies["Mycookie"] != null)
{
HttpCookie Cookie = Request.Cookies.Get("Mycookie");
Usertxt.Text=Cookie.Values["UserName"];
Passwordtxt.Text=Cookie.Values["Password"];
}
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
Literal LBL;
LBL = (Literal)Login1.FindControl("FailureText");
if (FormsAuthentication.Authenticate(Usertxt.Text, Passwordtxt.Text))
{
Response.Redirect("");
}
else
{
Login1.FindControl("FailureText");
LBL.Text = "error ocurred";
}
}
}
Thank you more I got the answer and this the right code
public partial class _Default : System.Web.UI.Page
{
public TextBox Usertxt, Passwordtxt;
public Literal LBL;
public CheckBox CHB;
protected void Page_Load(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
if (!IsPostBack)
{
if (Request.Cookies["MyCookie"] != null)
{
HttpCookie Cookie = Request.Cookies.Get("MyCookie");
Usertxt.Text = Cookie.Values["UserName"];
Passwordtxt.Text = Cookie.Values["Password"];
}
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
CHB = (CheckBox)Login1.FindControl("RememberMe");
LBL = (Literal)Login1.FindControl("FailureText");
HttpCookie MyCookie = new HttpCookie("MyCookie");
bool IsRememberme = CHB.Checked;
if (IsRememberme)
{
MyCookie.Values.Add("UserName", Usertxt.Text);
MyCookie.Values.Add("Password", Passwordtxt.Text);
MyCookie.Expires = DateTime.Now.AddDays(15);
}
else
{
MyCookie.Values.Add("UserName", string.Empty);
MyCookie.Values.Add("Password", string.Empty);
MyCookie.Expires = DateTime.Now.AddDays(5);
}
Response.Cookies.Add(MyCookie);
if (FormsAuthentication.Authenticate(Usertxt.Text, Passwordtxt.Text))
{
Response.Redirect("");
}
else
{
Login1.FindControl("FailureText");
LBL.Text = "error ocurred";
}
}
}