Ok so I am getting into programing in ASP.Net with C#. I am trying a very simple procedure but it is very buggy. So I have the following ASP code:
<asp:Button ID="Button1" runat="server" Text="Show Numbers" onclick="Button1_Click1" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server"
oncheckedchanged="CheckBox1_CheckedChanged" />
I then have the following C# code behind it:
int i = 0;
List<int> Chosen = new List<int>();
public void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click1(object sender, EventArgs e)
{
if (i == 0)
{
TextBox1.Text = "Nothing here!";
}
else if (i == 1)
{
TextBox1.Text = Chosen[0].ToString();
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
Chosen.Add(1);
i++;
CheckBox1.Checked = true;
}
else if (CheckBox1.Checked == false)
{
Chosen.Remove(1);
i--;
CheckBox1.Checked = false;
}
}
The goal of the code is to have a checkbox on the screen. If it is checked I want to add the number 1 to my list (Chosen) also, when I push the button I want the textbox to display the number 1. If the checkbox becomes unchecked I want the number to get removed from the list and when I push the button I want it to display "Nothing here!".
The problem is, sometimes it works and sometimes it doesn't. For example if I click the box then the button it works. Then when I click the button again it says "Nothing Here!" it should stay as a 1.
You have to set AutoPostBack=true to the CheckBox control markup and also save that list into Session dictinary.
List<int> Chosen;
public void Page_Load(object sender, EventArgs e)
{
if(Sesstion["Chosen"]==null)
{
Session["Chosen"]=new List<int>();
}
Chosen = (List<int>)Session["Chosen"];
}
Related
I have a textbox in an asp.net web page. In case of postback, I need to set focus on last char in this texbox. how can I do this using c# without using anything like jQueries..
Thanks
Here is a variation of the solution proposed in Use JavaScript to place cursor at end of text in text input element:
void btnPostBack_Click(object sender, EventArgs e)
{
txtFocus.Attributes["onfocus"] = "var value = this.value; this.value = ''; this.value = value; onfocus = null;";
txtFocus.Focus();
}
Your code like below :
asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ontextchanged="TextBox1_TextChanged" TabIndex="1">
asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" ontextchanged="TextBox2_TextChanged" TabIndex="2">
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void Page_PreRender(object sender, EventArgs e)
{
try
{
if (Session["event_controle"] != null)
{
TextBox controle =(TextBox) Session["event_controle"];
controle.Focus();
}
}
catch ()
{
}
}
I have a web-part in SharePoint 2013 which adds the new items from excel. The web-part contains upload control, buttons and textbox. I choose the document from upload control and click the button to load items in SP, if it was successfull I see "Successfull" in textbox or "Not successfull" in another way.
My problem: if i refresh page with web-part, textbox still contains the old text, but i want to see it empty after every refresh.
I try to use Page.IsPostBack, but I think I didn't properly use it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
textbox1.Text = "";
}
protected void btn3_Click(object sender, EventArgs e)
{
if (!Page.IsPostBack)
return;
if(!upload.HasFile)
{
textbox1.Text += "You didn't choose an Excel file";
return;
}
...
}
<asp:Button ID="btn3" runat="server" OnClick="btn3_Click" Text="Add Items" />
In such case, you can implement a special code block to detect browser refresh as
private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
refreshState = bool.Parse(AllStates[1].ToString());
if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}
protected override object SaveViewState()
{
Session["ISREFRESH"] = refreshState;
object[] AllStates = new object[3];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(refreshState);
return AllStates;
}
In the button click you can do it as
protected void btn3_Click(object sender, EventArgs e)
{
if (isRefresh == false)
{
Insert Code here
}
}
Enable Disable Checkbox in Asp.net Gridview Based on DropDownlist in C#
I have a problem with my C# code.
I need enable or disable checkboxes in asp.net gridview based on DropDownList.
If in the DropDownList no have selected any values the checkboxes in GridView are disabled.
When in the DropDownList have selected a value the checkboxes in GridView are enabled for the variable selected in the DropDownList.
In the GridView the output is correct when in DropDownList have selected a value, but Checkboxes are always enabled.
I've tried using these solution without success.
Here is my code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = (CheckBox)e.Row.FindControl("chkSelect");
if (DDL.SelectedIndex != 0)
{
chkSelect.Enabled = true;
}
}
}
catch (Exception)
{
}
}
edit #1
<asp:DropDownList ID="DDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DDL_SelectedIndexChanged"
CssClass="ddl_Class" Enabled="false">
<asp:ListItem Text="-------" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:TemplateField>
<ItemTemplate>
<center>
<asp:CheckBox ID="chkSelect" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged"
AutoPostBack="true" Enabled="false" /></center>
</ItemTemplate>
</asp:TemplateField>
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkSelect = ((CheckBox)GridView1.Rows[i].FindControl("chkSelect"));
if (DDL.SelectedIndex != 0)
{
chkSelect.Enabled = true;
}
}
GridViewBind();
}
you set check box Enable OR Disable On
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkSelect = ((CheckBox)GridView1.Rows[i].FindControl("chkSelect"));
if (DDL.SelectedIndex != 0)
{
chkSelect.Enabled = true;
}
}
}
Making the string lowercase should help?
Eval("Reason").ToString().ToLower().Equals("hybrid")
i need to assign value for selected value drop down in aspx for example
dropdownlist items
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
if user select any item in dropdownlist1 it should increment value 2 then
if user select any item in dropdownlist2 it should increment value 2
i need to display total
i tried this code
static int i = 0;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
its working but problem is if user first select 1 in dropdown //i=2 then user select b //i=4 if user again select 1 //i=6. it should not increment if user select any value in particular drop down list. how to do it. any idea....
You're using a static variable so the i value will be kept between postbacks and will be common to all users, this is incorrect.
You need to store it in ViewState, HiddenField, or Session in order to keep the value between postbacks and also keep the value different for each user.
Here's what I would've done using ViewState:
private int Counter
{
get
{
if (ViewState["Counter"] == null)
{
return 0;
}
else
{
return (int)ViewState["Counter"];
}
}
set
{
ViewState["Counter"] = value;
}
}
private bool DropDown1Selected
{
get
{
if (ViewState["DropDown1Selected"] == null)
{
return false;
}
else
{
return (bool)ViewState["DropDown1Selected"];
}
}
set
{
ViewState["DropDown1Selected"] = value;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.DropDown1Selected)
{
this.DropDown1Selected = true;
this.Counter += 2;
}
Label1.Text = string.Format("hello{0}", this.Counter);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
this.Counter += 2;
Label1.Text = string.Format("hello{0}", this.Counter);
}
Few of the answers above are talking about static variable getting reset after post back, this is incorrect, Static variables keep their values for the duration of the application domain. It will survive many browser sessions until you restart the web server Asp.net Static Variable Life time Across Refresh and PostBack
That being said, it is definitely not a good idea to use Static variables and instead go with the approaches suggested using Session or Viewstate.
About your question, I guess you want to increment the value only first time a value is chosen from the drop down list, to achieve this you would want to have a flag to let you know if the value is already selected, something on the below lines:
static bool DrpDown1;
static bool DrpDown2;
static int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DrpDown1 = false;
DrpDown2 = false;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown1)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown1 = true;
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown2)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown2 = true;
}
}
You need a temporary store like ViewState or Session to keep you values and get it back from
there.
private int GetValue()
{
return Int32.Parse(ViewState["temp"]);
}
private void SetValue(int i)
{
if(ViewState["temp"]==null)
{
ViewState["temp"]=i;
}
else
{
ViewState["temp"]= i+Int32.Parse(ViewState["temp"]);
}
}
and use it in your code as follows
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}
I am a noob and i've been trying to figure out how we may assign an ID to asp:TextBox tags on creation in ASP.NET using c#.
Example:
I need to create a thread that may have multiple textboxes.
When a user clicks on a button, a text box must be generated with an ID say, txt01. On being clicked the second time, the ID of the generated text box must be txt02 and so on..depending on the number of clicks.
Thanks in Advance.
Remember last ID in some variable, for example int lastID, then in button's onClick method when creating the new TextBox assign its ID="txt"+lastID;.
You have to persist the lastID during page postbacks, you can store it in a ViewState.
Take and placeholder in your aspx page: eg: <asp:PlaceHolder runat="server" ID="pholder" />
and in code behind:
TextBox txtMyText = new TextBox();
tb1.ID = YourDynamicId;
pholder.Controls.Add(txtMyText);
You can save current id in ViewState and get the same id and assign incremented id to your dynamic textbox.
Try This:
int i = 1;
if (ViewState["i"] == null)
{
ViewState["i"] = i;
}
else
i = (int)ViewState["i"];
PlaceHolder1.Controls.Clear();
for (int j = 1; j <= i; j++)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox" + j.ToString();
PlaceHolder1.Controls.Add(TextBox);
}
ViewState["i"] = i + 1;
add this on your .aspx page
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Hope This help.
I think this is what you are looking for -
You will notice that I have used Page_Init because if you create/add the controls in Page_Load then FindControl will return null in PostBack. And also any data you entered in the dynamically added controls will not persist during Postbacks.
But Page_Init is called before ViewState or PostBack data is loaded. Therefore, you can not use ViewState or any other controls to keep the control count. So I have used Session to keep the count.
Try it out and let me know what you think.
ASPX Page
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
store the id in a ViewState something like this
First initialise a count variable similiar to this.
in your class write this
protected int replyCount //declare the variable
{
get { return (int)ViewState["replyCount"]; }
set { ViewState["replyCount"] = value; }
}
In your page Load write this to initialise the replyCount if its not a postback;
protected void Page_Load(object sender, EventArgs e)
{
if(!page.IsPostBack)
{
replyCount = 0; //initialise the variable
}
}
then while creating dynamic textboxes
protected void Button_Click(Object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.id = "tb" + replycount; //use the variable
replycount++; // and after using increment it.
form.controls.add(tb); // assuming your form name is "form"
}
Thats it you should do.