check if button is clicked in if() condition aspx.net - asp.net

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)
}

Related

How to paint cells in row (Telerik)?

I've next code that handle fowFormatting my cells:
private void gridViewRaces_RowFormatting(object sender, RowFormattingEventArgs e)
{
foreach (var cellColumn in e.RowElement.Data.Cells)
{
var cellInfo = cellColumn as GridViewCellInfo;
if (cellInfo != null)
{
cellInfo.Style.DrawFill = true;
if (cellInfo.ColumnInfo.Name == "columnContactProducerName")
{
cellInfo.Style.DrawFill = true;
cellInfo.Style.BackColor = Color.Yellow;
}
else if (cellInfo.ColumnInfo.Name == "columnTransport")
{
cellInfo.Style.BackColor = Color.Yellow;
}
else
{
cellInfo.Style.BackColor = ColorTranslator.FromHtml((e.RowElement.Data.DataBoundItem as RaceForListDto).Color);
}
}
}
//e.RowElement.BackColor = ColorTranslator.FromHtml((e.RowElement.Data.DataBoundItem as RaceForListDto).Color);
}
but my cells aren't painting. How to paint some cells in rows on dataBinding?
It looks like the proper event to do this is ItemDataBound event. See here:
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/appearance-and-styling/conditional-formatting
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
//Is it a GridDataItem
if (e.Item is GridDataItem)
{
//Get the instance of the right type
GridDataItem dataBoundItem = e.Item as GridDataItem;
//Check the formatting condition
if (int.Parse(dataBoundItem["Size"].Text) > 100)
{
dataBoundItem["Received"].ForeColor = Color.Red;
dataBoundItem["Received"].Font.Bold = true;
//Customize more...
}
}
}
Or event better is to use a custom CSS class so that you can later make changes without having to rebuild the project:
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e){
if (e.Item is GridDataItem)
{
GridDataItem dataItem = e.Item as GridDataItem;
if (dataItem["Country"].Text == "Mexico")
dataItem.CssClass = "MyMexicoRowClass";
}
}

Force String.Format "{0:P4}" to show + sign

I have a decimal column in my Database where values are stored as 12.35
We show it as 12.35%
The client wants to show +12.35% if the value is positive(just for this one field). How I do get it to show the +sign.
We format the textedit as P4 in the getter String.Format("{0:P4}", value);
This is what I've tried:
I was able to do this by using Fomrat event handler. I am looking for a cleaner way instead of the below code.
private void txtMargin_FormatEditValue(object sender, DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs e)
{
if (e.Value != null)
{
if (e.Value.ToString().IndexOfAny(new char[] { '-', '+' }) < 0)
{
string val = e.Value.ToString();
val = val.Replace("%", "");
e.Value = string.Format("+{0}", (Convert.ToDouble(val) / 100).ToString("P4"));
e.Handled = true;
}
else
{
string val = e.Value.ToString();
val = val.Replace("%", "");
e.Value = (Convert.ToDouble(val) / 100).ToString("P4");
}
e.Handled = true;
}
}
private void txtMargin_ParseEditValue(object sender, DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs e)
{
if (e.Value != null)
{
if (e.Value.ToString().IndexOf('%') < 0)
{
e.Value = (Convert.ToDouble(e.Value.ToString()) / 100).ToString("P4");
}
}
}
In your form load past this code :
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textEdit1.Properties.Mask.EditMask = "+#0.0000% ;-#0.0000%";
textEdit1.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
textEdit1.Properties.Mask.UseMaskAsDisplayFormat = false;
textEdit1.Properties.EditFormat.FormatString = "+#0.0000% ;-#0.0000%";;
}
And in you TextBox Handel the event "`CustomDisplayText`" as :
private void textEdit1_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
{
if (e.Value != null && !e.Value.Equals (""))
e.DisplayText = (Convert.ToDouble(e.Value.ToString()) / 100).ToString("+#0.0000 % ;-#0.0000 %");
}

UserAccounts_RowEditing/Updating is not working properly

Alright, so I have a Gridview and added RowEditing and RowUpdating to it, but it won't really edit something.. This is my code for both:
protected void UserAccounts_RowEditing(object sender, GridViewEditEventArgs e)
{
UserAccounts.EditIndex = e.NewEditIndex;
BindUserAccounts();
}
protected void UserAccounts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = UserAccounts.EditIndex;
GridViewRow row = UserAccounts.Rows[e.RowIndex];
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
email = ((TextBox)row.Cells[2].Controls[0]).Text;
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
user.Email = email;
Membership.UpdateUser(user);
ActionStatus.Text = string.Format("User {0} details have been successfully updated!", username);
}
UserAccounts.EditIndex = -1;
BindUserAccounts();
}
What am I doing wrong in here?
EDIT: This is my BindUserAccounts:
private void BindUserAccounts()
{
int totalRecords;
UserAccounts.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
UserAccounts.DataBind();
bool visitingFirstPage = (this.PageIndex == 0);
lnkFirst.Enabled = !visitingFirstPage;
lnkPrev.Enabled = !visitingFirstPage;
int lastPageIndex = (totalRecords - 1) / this.PageSize;
bool visitingLastPage = (this.PageIndex >= lastPageIndex);
lnkNext.Enabled = !visitingLastPage;
lnkLast.Enabled = !visitingLastPage;
}
i think the should be like this
protected void update_click_foredu(object sender, GridViewUpdateEventArgs e)
{
Label edui = (Label)edugrid.Rows[e.RowIndex].FindControl("label");
TextBox unitxt = (TextBox)edugrid.Rows[e.RowIndex].FindControl("txtuni");
if (unitxt != null && costxt != null && startdatetxt != null && enddatetxt != null)
{
using (Entities1 context = new Entities1())
{
string eduID = edui.Text;
model obj = context.entitytabel.First(x => x.ID == eduID);
obj.Univ_Name = unitxt.Text;
context.SaveChanges();
lblMessage.Text = "Saved successfully.";
edugrid.EditIndex = -1;
bindgrid();
}
}
}
here im using EF like this you can find the control of the text box and save it in gridview
hope this helps you
Somehow it works now after editing the GridView and set "UserName", "IsApproved", "IsLockedOut" and "IsOnline" to ReadOnly="true"

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;
}
}

Login page fault

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";
}
}
}

Resources