Add values to global List - c#

I have the following global List -
public partial class About : System.Web.UI.Page
{
List<string> changes = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> changes = new List<string>();
}
I am trying to add string values to changes like so -
protected void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
DataListItem item = (DataListItem)chk.NamingContainer;
TextBox txt = (TextBox)DataList1.Items[item.ItemIndex].FindControl("aliasTextBox");
string text = txt.Text;
changes.Add(text);
ViewState["array"] = changes;
}
So I am trying to store all changes made in the dataList into changes so that when a user clicks -
protected void Button5_Click(object sender, EventArgs e)
{
List<string> changes = (List<string>)ViewState["array"];
foreach (string text in changes)
{
WebService1 ws = new WebService1();
ws.WebMethod(text);
}
}
However when it comes to clicking the button, I get a null reference exception on the - changes.add(text) section. How can I store all the values in changes to be available on button click?

The changes that you are making to a variable will not persist after the postback. You should save the value of this list 'changes' to a viewstate, session or application so that you can retain the values of the list even after the postback.
Add this code in the CheckBox1_CheckedChanged event after updating the list
ViewState["Somename"]=changes;
Add this code in the Button5_Click before accessing the list
changes= (List<string> )ViewState["Somename"]

Use IsPostBack
and change your List<string> changes = new List<string>(); to List<string> changes = null;
Add this code to your constructor
if(!IsPostBack)
{
changes = new List<string>();
}
Other wise you can use ViewState

Related

Cannot get value from database-bound dropdownlist

I'm using asp.net 4.5 web forms with VS2017 and using dropdownlist to get the values
from the database and try to get the value but it keeps giving me only the top value, so I'm asking for help.
The way I binded the value is this :
protected void Page_Load(object sender, EventArgs e)
{
var db = new dbContext();
var CustItem = db.customer.ToList();
customerDropDownList.DataSource = CustItem;
customerDropDownList.DataTextField = "cust";
customerDropDownList.DataValueField = "cust";
customerDropDownList.DataBind();
}
and it works nicely and gets all the list in customer table and populates the data in cust column in the id : customerDropDownList.
And then I tried to get the value from customerDropDownList by having a testBtn
with testLbl attached and used
protected void testBtn_Click(object sender, EventArgs e)
{
testLbl.Text = customerDropDownList.SelectedValue;
}
and it only selects the top element always.
I suspect this has to do with the lifecycle of asp.net and am studying about it
but cannot find the clear answer to solve this.
Could anyone help me on this?
Probably because you are resetting the dropdown list on each page load. Try only setting the ddlist the first time.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
var db = new dbContext();
var CustItem = db.customer.ToList();
customerDropDownList.DataSource = CustItem;
customerDropDownList.DataTextField = "cust";
customerDropDownList.DataValueField = "cust";
customerDropDownList.DataBind();
}
}
you are missing Page.IsPostBack in page load event
more on Ispostback here
With your code are you not noticing your dropdown list is doubled on the click ?
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
var db = new dbContext();
var CustItem = db.customer.ToList();
customerDropDownList.DataSource = CustItem;
customerDropDownList.DataTextField = "cust";
customerDropDownList.DataValueField = "cust";
customerDropDownList.DataBind();
}
}
Make sure to load the dropdown only once. your page load will be called on the button click as well.
Keep a break point and play around !! Good luck

Add and delete text to/from ListBox hosted in WinForm using C#

I am working on a simple application that to add/delete string/s into an array and show that in ListBox.
My code shows only the latest value that was typed into the textBox and
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
List<string> ls = new List<string>();
ls.Add(add);
String[] terms = ls.ToArray();
List.Items.Clear();
foreach (var item in terms)
{
List.Items.Add(item);
}
}
private void Delete_Click(object sender, EventArgs e)
{
}
This code makes no sense. You are adding one single item to a list, then convert it to an array (still containg one item) and finally loop through this array, which of course adds one item to the previously cleared listbox. Therefore your listbox will always contain one single item. Why not simply add the item directly?
private void Add_Click(object sender, EventArgs e)
{
List.Items.Add(textBox1.Text);
}
private void Delete_Click(object sender, EventArgs e)
{
List.Items.Clear();
}
Also clear the listbox in Delete_Click instead of Add_Click.
If you prefer to keep the items in a separate collection, use a List<string>, and assign it to the DataSource property of the listbox.
Whenever you want the listbox to be updated, assign it null, then re-assign the list.
private List<string> ls = new List<string>();
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
// Avoid adding same item twice
if (!ls.Contains(add)) {
ls.Add(add);
RefreshListBox();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Delete the selected items.
// Delete in reverse order, otherwise the indices of not yet deleted items will change
// and not reflect the indices returned by SelectedIndices collection anymore.
for (int i = List.SelectedIndices.Count - 1; i >= 0; i--) {
ls.RemoveAt(List.SelectedIndices[i]);
}
RefreshListBox();
}
private void RefreshListBox()
{
List.DataSource = null;
List.DataSource = ls;
}
The problem with code is quite simple. Instead of adding new item to list your code creates new list with one added item only. I am trying to interpret functions of program and they seem to be:
Enter new text into top level text box.
If Add button is clicked your item goes on top of the list (if it's bottom see end of my answer).
If item(s) is selected in list and Delete is clicked selected item(s) is/are deleted.
To achieve this you should first insert text on top of the list by using Add_Click code, than delete selected items using Delete_Click code. There is additional code to guard against inserting empty or white space only strings plus trimming of leading and trailing white space.
private void Add_Click(object sender, EventArgs e)
{
// Since you do not want to add empty or null
// strings check for it and skip adding if check fails
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text)
{
// Good habit is to remove trailing and leading
// white space what Trim() method does
List.Items.Insert(0, textBox1.Text.Trim());
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Get all selected items indices first
var selectedIndices = List.SelectedIndices;
// Remove every selected item using it's index
foreach(int i in selectedIndices)
List.Items.RemoveAt(i);
}
To complete adding and deleting logic I would add Delete All button which would just call List.Items.Clear(). If you prefer to add text at the end just use Add method form #Olivier Jacot-Descombes answer.
You can use in C#:
private void Delete_Click(object sender, EventArgs e)
{
if(myList.Contains(textbox1.value))//if your list containt the delete value
{
myList.Remove(textbox1.value); //delete this value
}
else
{
//the list not containt this value
}
}
and you can use the same method for validate if a value exist when try to add
private void AddItem()
{
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text))
{
var newItem = textBox1.Text.Trim();
if (!List.Items.Contains(newItem))
{
List.Items.Add(newItem);
// Alternative if you want the item at the top of the list instead of the bottom
//List.Items.Insert(0, newItem);
//Prepare to enter another item
textBox1.Text = String.Empty;
textBox1.Focus();
}
}
}
private void Add_Click(object sender, EventArgs e)
{
AddItem();
}
Private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
AddItem();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Remove every selected item using it's index
foreach(var item in List.SelectedItems)
{
List.Items.Remove(item);
}
}

Dynamically or button click Search specific tab in tab control in c#

i making some application for my office and in this application there are so many tabs (more than 50) i want to search tabs using textbox ,if its possible can someone kind enough to show how can i search dynamically instead clicking a search button
this is my code that i tried
private void button62_Click(object sender, EventArgs e)
{
if (secondtabcontainer.TabPages.ContainsKey.Equals("chattextbox"))
secondtabcontainer.SelectedTab = secondtabcontainer.TabPages["tabPage17"];
}
private void textBox55_TextChanged(object sender, EventArgs e)
{
string chattextbox;
chattextbox = textBox55.Text;
}
Try this in TextChanged event:
private void textBox55_TextChanged(object sender, EventArgs e)
{
string sTabName = textBox55.Text;
foreach (TabPage tab in secondtabcontainer.TabPages)
{
if (sTabName.Equals(tab.Name))
{
secondtabcontainer.SelectedTab = tab;
break;
}
}
}
You should maintain a dictionary (Dictionary<string, string>) containing "Tab Display Name-TabID" pairs:
Dictionary<string, string> tabs = new Dictionary<string, string>();
// sample entries
tabs.Add("First Tab", "tab1");
tabs.Add("Second Tab", "tab2");
// ...
tabs.Add("chattextbox", "tab17");
Then add the tabs to the Items collection on a new ComboBox control.
Add your code to the SelectedValueChanged' event handler attached to theComboBox`.
// `TabsList` is a new control that make the tabs searchable.
protected void TabsList_SelectedValueChanged(object sender, EventArgs e)
{
if (TabsList.SelectedIndex != -1)
{
var tabid = tabs[TabsList.SelectedText];
secondtabcontainer.SelectedTab = secondtabcontainer.TabPages[tablid];
}
}
This should allow you to type-ahead the name of a tab and automatically switch once you've made you selection.

how to bind more than one dropdownlist without refreshing?

protected void Page_Load(object sender, EventArgs e)
{
bindbranches();
bindbranches1();
}
public void bindbranches()
{
DataTable dtbranch = new DataTable();
dtbranch = objsupplyBAL.getbrnch();
ddlbranch.DataSource = dtbranch;
ddlbranch.DataBind();
ddlbranch.Items.Add(new ListItem("--select--", "0"));
ddlbranch.SelectedIndex = ddlbranch.Items.Count - 1;
}
public void bindbranches1()
{
DataTable dt = new DataTable();
dt = objsupplyBAL.getbrnch();
ddlbranch1.DataSource = dt;
ddlbranch1.DataBind();
ddlbranch1.Items.Add(new ListItem("--select--", "0"));
ddlbranch1.SelectedIndex = ddlbranch1.Items.Count - 1;
}
My dropdownlist's are not binding without refreshing.If i select one dropdownlist another one is refreshing. What i have to add extra to my code. Can any one tell...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
bindbranches();
bindbranches1();
}
}
if you add this...it's work properly ...first try this...
The reason that is happening is you are running the code every time the page postsback, try the following to only populate the items once (on the initial page load) :
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack) {
bindbranches();
bindbranches1();
}
}
Alternatively you can also handle the Page.Init event to run this code, this will change the dropdowns when the page is first loaded and will keep the values throughout subsequent postbacks :
protected void Page_Init(object sender, EventArgs e) {
bindbranches();
bindbranches1();
}
If you want the second dropdown to refresh only when the first item is selected, try the following solution :
protected void ddlbranch_SelectedIndexChanged(object sender, EventArgs e) {
bindbranches1();
}
And bind ddlbranch_SelectedIndexChanged to the selected index changed event of your ddlbranch control. This will only run the code when the page is initially loaded and when the user selects an item from the ddlbranch dropdown
You will have to set AutoPostBack Property of the drop down to true if you want to fill another drop down on change of one drop down so on change event will start executing
Loot # http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.autopostback.aspx

Creating, Using and Discarding Temporary Value not working

I am trying to assign a ViewState value in my application with a SelectedIndexChanged function. Once it's assigned the postback will use the value to change some data and then set the value to zero but I can't seem to get it to work correctly. The controls are all created dynamically on Page_Load.
Page Load
protected void Page_Load(object sender, EventArgs e)
{
CreateAttributeControls();
TempProductVariantId = 0;
}
Create Attribute Controls
public void CreateAttributeControls()
{
...
var ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.SelectedIndexChanged += new EventHandler(ArtistArtwork_SelectedIndexChange);
ddlArtistArtworks.AutoPostBack = true;
...
}
ArtistArtwork_SelectedIndexChange
protected void ArtistArtwork_SelectedIndexChange(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
TempProductVariantId = int.Parse(ddl.SelectedValue);
}
TempProductVariantId ViewState Save
public int TempProductVariantId
{
get
{
if (ViewState["TempProductVariantId"] == null)
return 0;
else
return (int)ViewState["TempProductVariantId"];
}
set
{
ViewState["TempProductVariantId"] = value;
}
}
When I load the page everything is fine. I change the DropDownList's value, It posts back, and the value is not set. Change it again the value is set and continues to change as I change the value of the DropDownList.
Any guidance on this would be greatly appreciated.
Note: I have tried changing when CreateAttributeControls() is called. In OnPreRender for example. I was given this to understand the lifecycle of the page Life Cycle
That's because you are essentially recreating the dropdown on every postback..
try this
public void CreateAttributeControls()
{
...
DropDownList ddlArtistArtworks;
if (!IsPostBack)
{
ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.AutoPostBack = true;
}
else
{
ddlArtistArtworks = (DropDownLise)divAttribute.FindControl("ddlArtistArtworksTest");
}
ddlArtistArtworks.SelectedIndexChanged += new EventHandler(ArtistArtwork_SelectedIndexChange);
...
}
For dynamically added controls, the event handler has to be linked up everytime so that has to be done outside the if-block, unconditionally.

Categories

Resources