I'm trying to get checkbox list values to a single string. in ASP.net using C#.
Here's my code.. I have declared this globally.
string hobbies = "";
This is the code to get the selected items to a string.
protected void chkListHobbies_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i=0;i<chkListHobbies.Items.Count;i++)
{
if (chkListHobbies.Items[i].Selected)
{
hobbies += chkListHobbies.Items[i].Value + ",";
}
}
hobbies = hobbies.TrimEnd(',');
I'm displaying this on button click
protected void btnEnter_Click(object sender, EventArgs e)
{
Response.Write("Hobbies= "+hobbies);
}
It doesn't give the expected output.
Would like to get this corrected if it's wrong or would like to know how to do it properly.
Thanks in advance.
You have to create hobbies list in your btnEnter_Click event handler because Asp.net webforms in stateless and you'll get a new hobbies variable after each postback. To address this issue you have to save hobbies state somehow (using viewstate or a hidden field) and use it later or as I suggested create hobbies list in btnEnter_Click.
Edit (examples):
1.Do the whole thing in btnEnter_Click:
protected void btnEnter_Click(object sender, EventArgs e)
{
string hobbies = "";
for (int i=0;i<chkListHobbies.Items.Count;i++)
{
if (chkListHobbies.Items[i].Selected)
{
hobbies += chkListHobbies.Items[i].Value + ",";
}
}
hobbies = hobbies.TrimEnd(',');
Response.Write("Hobbies=" + hobbies);
2.Use ViewState:
private string hobbies
{
get { return (ViewState["hobbies"] ?? "").ToString(); }
set { ViewState["hobbies"] = value; }
}
and the rest of your code is exactly the same.
Related
I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)
i'm requesting data from database through a D A L file. I want to data bind and show a drop down menu's single option selected against that of the database. How should i do it?
here's my code:
Pages pg = new Pages();
public static string pgId;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Bind_ddlParentPage();
Bind_ddlPageModel();
Bind_ddlArticleModel();
if (!IsPostBack)
{
pgId = Request.QueryString["pageId"];
if (pgId != null)
{
GetData();
}
}
}
}
public void GetData()
{
ddlParentPage.SelectedValue = pg.ParentPage;
//Bind_ddlParentPage();---dropdownlist which is causing problem.
//I want to set this data:: pg.ParentPage to dropdownlist in another
page
ddlPageModel.SelectedValue = pg.PageModel;
//Bind_ddlPageModel();
//All the three drop downs have same table for the source,
'Pages' table and this page is the same page for adding new entry to
Pages table.
ddlArticleModel.SelectedValue = pg.ArticleModel;
//Bind_ddlArticleModel();
}
First, you have a duplication in your conditional statement:
if(!IsPostBack) {
...
if(!IsPostBack) {
...
}
}
Second, you need to bind the data to the dropdown, then set the selected value. Refer: this post
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
}
}
So, I have a simple ListView that users can add information to and a delete button that is only capable of deleting one selected item at a time. I'm trying to make it so that when multiple items are selected and 'delete' is pressed it deletes those selected items instead of just one. Your help is appreciated!
Add recipient code:
private void addtoRecipients_Click(object sender, EventArgs e)
{
if (recipientEmailBox.Text != "")
{
string[] S = new string[4];
S[0] = recipientEmailBox.Text;
S[1] = recipientNameBox.Text;
S[2] = txtLocation.Text;
S[3] = txtSubject.Text;
ListViewItem I = new ListViewItem(S);
recipientBox.Items.Add(I);
UpdateNoOfEmails();
}
}
My Delete Button Code (only deletes one selection at the moment)
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try { recipientBox.Items.Remove(recipientBox.SelectedItems[0]); }
catch { }
UpdateNoOfEmails();
}
Clear All Recipients Code
private void clearBTN_Click(object sender, EventArgs e)
{
recipientBox.Items.Clear();
UpdateNoOfEmails();
}
In my case, the simplest way to do it was with a while loop. This is what my new delete button code looks like:
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try
{
while (recipientBox.SelectedItems.Count > 0)
{
recipientBox.Items.Remove(recipientBox.SelectedItems[0]);
}
}
catch { }
UpdateNoOfEmails();
}
hi guy i am trying to place my session in to a drop down, any help would be great.
at the moment it puts the data in to a label, i wish to put it into a dropdown with it adding a new string every time i click button without getting rid of the last
default page
protected void Button1_Click1(object sender, EventArgs e)
{
Session["Fruitname"] = TbxName.Text; // my session i have made
}
output page
protected void Page_Load(object sender, EventArgs e)
{
var fruitname = Session["Fruitname"] as String; // my session ive made
fruit.Text = fruitname; // session used in lable
}
Have Tried
var myFruits = Session["Fruitname"] as List<string>;
myFruits.Add(listbox1.Text);
but i get error when i try to run the program
Broken glass thanks for your help, it is still not doing what i need but its getting there.
var fruitname = Session["Fruitname"] as String; // my session ive made
fruit.Text = string.Join(",", fruitname); // session used in lable
this is what is working. i need a dropdown to display all the strings put into TbxName.Text; to output into fruit
Just use a List<string> instead of a string then.
var myFruits = Session["Fruitname"] as List<string>;
myFruits.Add(TbxName.Text);
Has been fixed using code found else where
button page code bellow
protected void Button1_Click1(object sender, EventArgs e)
{
// Session["Fruitname"] = TbxName.Text; // my session i have made
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
MyFruit.Add(TbxName.Text);
Session["Fruitname"] = MyFruit;
{
public List<string> MyFruit { get; set; }
}
page where display
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
ListBox1.DataSource = MyFruit;
ListBox1.DataBind();
}
public List<string> MyFruit { get; set; }
}
I need help to get a response when I click on an "Item" from a list view. Know that there is selectedindexchanged, but when I try to display a MessageBox so nothing happens, have tried lots of other things but have not managed to come up with something.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
...
while (reader.Read())
{
string alio = reader["fornamn"].ToString();
string efternamn = reader["efternamn"].ToString();
ListViewItem lvi = new ListViewItem(alio);
listView1.Items.Add(lvi);
lvi.SubItems.Add(efternamn);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
Assuming that 81.private void listView1_SelectedIndexChanged is properly linked to the listview, you will need to query the listview to find out what's selected:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.listView1.SelectedItems.Count == 0)
return;
string namn = this.listView1.SelectedItems[0].Text;
// Create the sql statement to retrieve details for the user
string sql = string.Format("select * from kunder where fornamn = '{0}', namn);
// do the same as you do to create a reader and update the controls.
}
Going by the term "when I try to display a MessageBox so nothing happens"\, I assume that you simply put MessageBox.Show("blah"); inside the event handler and never got it shown.
If that's the case, your event handler is not hooked properly to your form's list view. go back and see the text listView1_SelectedIndexChanged is anywhere to be found inside your Form1.Designer.cs file.
If not (or anyway), start over on a new form. That's the easiest way out. :)
private void lstView_KQ_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstView_KQ.SelectedItems.Count > 0)
{
ListViewItem itiem = stView_KQ.SelectedItems[lstView_KQ.SelectedItems.Count - 1];
if (itiem != null)
foreach (ListViewItem lv in lstView_KQ.SelectedItems)
{
txtMaNV.Text = lv.SubItems[0].Text;
cmbCV.Text = lv.SubItems[1].Text;
txtHoNV.Text = lv.SubItems[2].Text;
txtTenNV.Text = lv.SubItems[3].Text;
txtNgaysinh.Text = lv.SubItems[4].Text;
txtGioiTinh.Text = lv.SubItems[5].Text;
txtDiaChi.Text = lv.SubItems[6].Text;
txtSDT.Text = lv.SubItems[7].Text;
txtCMND.Text = lv.SubItems[8].Text;
}
}
}