ASP.NET lisbox - Selected first item, always - asp.net

I have a list box which is populated using a dictioanry. When I iterate throught the selected items using the following code, it always show only the first items as selected - even if the first item is not selected.
Have you ever encountered this scenario?
Could you please help on this?
This problem occurs when I use dictionary for binding. On the other hand a generic list works fine.
private void PopulateListBox2()
{
List<string> subjectList = new List<string>();
subjectList.Add("Maths");
subjectList.Add("Science");
ListBox1.DataSource = subjectList;
ListBox1.DataBind();
}
Even it will work fine, if the values are unique. But in my scenario, the values are same; only key varies. The following works
private void PopulateListBox5()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo1");
resultDictionary.Add("Science", "Lijo2");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
^^^^^^^^^^^^^^^^^^^
The following code has the problem.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateListBox1();
ListBox1.SelectionMode = ListSelectionMode.Multiple;
}
}
private void PopulateListBox1()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo");
resultDictionary.Add("Science", "Lijo");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
MakeList1Items();
}
private void MakeList1Items()
{
string test = null;
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected == true)
{
if(string.IsNullOrEmpty(test))
{
test=item.Text;
}
else
{
test = test +", " + item.Text;
}
}
}
Response.Write(test);
}
}
Thanks
Lijo

You have the DataValueField and DataTextField of the ListBox the wrong way around. I'm not sure why, but they must be like this:
ListBox1.DataValueField = "Key";
ListBox1.DataTextField = "Value";
So, in reality, you are best not using a Dictionary for for this kind of binding. Maybe try a List<KeyValuePair<string, string>> instead.

Related

ASP.NET DropdownList Always insert the first item

I have dropdownlist on my website. When I select the any item to insert the database but it does not insert selected item always insert the first item inside the dropdown list. Please Help How can I solve that problem?
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategory();
}
}
void GetCategory()
{
dlCategory.DataSource = Data.GetDataTable("SELECT * FROM tblCategory");
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}
SqlConnection baglanti = Data.baglan();
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values(#CategoryID)", baglanti);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
Your question is a bit blurry regarding the code, so correct me if I misunderstood, but I presume you want to do the following in WebForms:
Simply show all available categories that can be assigned to a
product
When the user selects the category and hits submit, it will be inserted to the DB assegnied to it
It is not quite elegant, but I would put something like this:
private SqlConnection _sqlConnection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
_sqlConnection.ConnectionString = #".." //Assign whatever your ConnectionString is in Data.baglan();
_sqlConnection.Open();
if (!IsPostBack)
{
GetCategory();
}
else
{
//Define your insert something like this, and I would put this into the submit Button_Click event:
if (!String.IsNullOrEmpty(dlCategory.SelectedValue) && dlCategory.SelectedValue != "0")
{
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values (#CategoryID)", _sqlConnection);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
}
else
{
//TODO: Handle wrong selection, eg display an error message..
}
}
}
void GetCategory()
{
dlCategory.DataSource = new SqlCommand("SELECT * FROM tblCategory", _sqlConnection).ExecuteReader();
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}

View state or Hidden Field

I have to store eight to ten values in variables which are available even after post back.
I tried using Hidden Field but value is lost on post back. I am now using View state , but it seems it is degrading performance.
I have ten View State fields. what should I use to avoid poor performance ?
You can store Dictionary in ViewState.
private Dictionary<string, string> MyValues
{
get
{
var value = ViewState["MyValues"] as Dictionary<string, string>;
return value ?? new Dictionary<string, string>();
}
set { ViewState["MyValues"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var myValues = new Dictionary<string, string>
{
{"One", "1"}, {"Two", "2"}, {"Three", "3"}
};
MyValues = myValues;
}
else
{
string value1 = MyValues["One"];
string value2 = MyValues["Two"];
string value3 = MyValues["Three"];
}
}

object reference not to set an instance of an object

in the detail view , i have the user control and i like fill the propeties of that with
foreach (var file in fileList.Efiles)
but i have the error "object reference not to set an instance of an object" for (fileList.Efiles)
please help what is the problem
the complete code is like below:
public partial class DocResult : System.Web.UI.Page
{
private EDMSDataContext _DataContext;
private int _TransmittalId;
private int _DocId;
protected void Page_Load(object sender, EventArgs e)
{
String tmpString1;
String tmpString2;
tmpString1 = Request.QueryString["DocId"];
if (String.IsNullOrEmpty(tmpString1))
throw new ArgumentNullException("DocId");
_DocId = Convert.ToInt32(tmpString1);
tmpString2 = Request.QueryString["TransID"];
if (String.IsNullOrEmpty(tmpString2))
throw new ArgumentNullException("TransID");
_TransmittalId = Convert.ToInt32(tmpString2);
_DataContext = new EDMSDataContext();
var query = _DataContext.spDocResult(_DocId, _TransmittalId);
DetailsView1.DataSource = query.ToList();
DetailsView1.DataBind();
spDocResultResult docresult = (spDocResultResult)DetailsView1.DataItem;
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
foreach (var file in fileList.Efiles)
{
file.FileName = docresult.Filename;
}
fileList.DataBind();
}
}
Try below code
if(fileList!=null)
{
foreach (var file in fileList.Efiles)
{
file.FileName = docresult.Filename;
}
fileList.DataBind();
}

How to select Listbox value in asp.net

I have a ListBox in my webpage that is bound from database in this way:
ListBox1.DataTextField = "Text";
ListBox1.DataValueField = "MenuID";
ListBox1.DataSource = SqlHelper.ExecuteReader(DAL.DALBase.ConnectionString, "GetMenu");
ListBox1.DataBind();
I want to get selected item value and used this code but have a error and does not worked.
ListBox1.SelectedValue;
Forgive me if I have problems on how to write because my English is not good.
Can you be more specific on the error you are getting?
Using ListBox1.SelectedValue should work.
For example:
int mySelectedValue = int.Parse(ListBox1.SelectedValue);
or
string mySelectedValue = ListBox1.SelectedValue;
Edit
Added code to ensure the original poster was keeping values in ListBox databound.
protected void Page_Load( object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListBox();
}
}
private BindListBox()
{
ListBox1.DataTextField = "Text";
ListBox1.DataValueField = "MenuID";
ListBox1.DataSource = SqlHelper.ExecuteReader(DAL.DALBase.ConnectionString, "GetMenu");
ListBox1.DataBind();
}
protected void SomeButton_Click( object sender, EventArgs e)
{
string mySelectedValue = ListBox1.SelectedValue;
}

asp.net listbox vs winforms listbox

The following code is for winforms:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.DataSource = Fruit.Get();
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";
}
private void listBox1_Click(object sender, EventArgs e)
{
object li = listBox1.SelectedItem;
Fruit fr = (Fruit) li;
label1.Text = fr.Name;
}
}
Is it possible to use the same technique in asp.net?
If no, then what is the alternative?
No, it's not possible in ASP.NET.
As an alternative, you can store your fruit items in Dictionary<string, Fruit> collection and you can get your selected Fruit like that :
// Assume that your datasource is Dictionary<string, Fruit> myFruits
Fruit fr = myFruits[listBox1.SelectedValue];
I don't think you can do it exactly like that, as I'm quite rusty in winforms, but here's how i'd try it in asp.net
1.) Bind your listbox in Page_PreRender()
listBox1.DataSource = Fruit.Get();
listBox1.DataTextField = "Name";
listBox1.DataValueField = "ID";
listBox1.DataBind();
2.) I'm not sure what the equivalent "OnClick" event would be, but you could hook into the SelectedIndexChanged event like so (triggered by another button):
var li = listBox1.SelectedItem;
label1.Text = li.Text;

Resources