asp.net listbox vs winforms listbox - asp.net

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;

Related

unable to persist data on postback in dotnetnuke7

I have my website running on dotnetnuke 7.4, i have a checklistbox which i bind on the page load, and after selecting items from it, user clicks on the submit button, the selected items should save in database, however when i click on the submit button, checklistbox gets blank, i tried to enable ViewState at :
Web.config level
Page Level
Control Level
But all in vain, it still unbinds checklistbox because of which everything disappears, i tried the same in plain .net and it works like a charm.
Is there any specific settings in dotnetnuke to support viewstate, or is there any other better option to achieve this.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in chkBox.Items)
Response.Write(item.Text + "<br />");
}
There's the issue. Remove that (!IsPostBack) check in your page_load event. Have your code to be like below. Else, only at first page load you are binding the datasource to control which gets lost in postback.
protected void Page_Load(object sender, EventArgs e)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
OR, to be more efficient; refactor your code to a method like below and store the data object in Session variable like
private void GetDataSource()
{
List<Entities> obj = null;
if(Session["data"] != null)
{
obj = Session["data"] as List<Entities>;
}
else
{
Entities objEntities = new Entities();
obj = objEntities.GetList(2);
}
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
Session["data"] = obj;
}
Call the method in your Page_Load event like
protected void Page_Load(object sender, EventArgs e)
{
GetDataSource();
}

How to bind a List<string> to GridView in ASP.NET?

I am hitting an API and storing the returned parsed data to a List. Currently I am displaying the data in the ListView.
I am not able display the same list in a GridView. Can anyone guide me how to do it?
This is my aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
ComodityList obj_comodity_in = (ComodityList)Session["comodity_list"];
Label1.Text = obj_comodity_in.status_code;
Label2.Text = obj_comodity_in.count.ToString();
//ComodityList obj_comodity_in = (ComodityList)Session["comodity_list"];
List<String> commodity_names = null;
getComodityNames(out commodity_names, obj_comodity_in);
ListView1.DataSource = commodity_names;
ListView1.DataBind();
}
private void getComodityNames(out List<String> commodity_names, ComodityList cl)
{
commodity_names = new List<string>();
foreach (Commodity c in cl.data)
{
commodity_names.Add(c.commodity);
commodity_names.Add(c.state);
commodity_names.Add(c.market);
commodity_names.Add(c.Maximum_Price.ToString());
commodity_names.Add(c.Minimum_Price.ToString());
commodity_names.Add(c.Modal_Price.ToString());
commodity_names.Add(c.origin);
commodity_names.Add(c.unit);
commodity_names.Add(c.variety);
}
}
Set AutoGenerateColumns property to true will help you.
Default.aspx:
<asp:GridView ID="GridView1" runat="server" Width="95%" autogeneratecolumns = "false">
Default.aspx.cs:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> s = new List<string>() { "a", "b", "c" };
this.GridView1.DataSource = s;
this.GridView1.DataBind();
}
}
If you don't want to change the API (you still want to return a list of strings) and need to use a grid you could create a new class containing the properties you already had in Commodity and simply rehydrate the class using the lists string data. Each new 'Commodity' class could go in a new List<Commodity> and you can bind that to the grid.
On the other hand - it's probably better to reconsider what you are actually trying to achieve and then redesign the API if that is an option.

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

CRUD Operations with DetailsView and EntityDataSource in Custom Server Control

I am not a big fan of ASPX pages, drag-and-drop and so on. I'm building a portal with a single Default.aspx and every other thing is custom web part controls or server controls that other developers can build in compiled dll and users can upload to the portal themselves to add features to the portal. I've been battling with DetailsView crud operations with entitydatasource. I did a test.aspx page with drag and drop and everything worked fine but with 100% code behind, nothing is. No error is displayed but data are not being persisted to database. I tried catching the onUpdating event of the detailsview and yes the event was fired and I could enumerate the data submitted but why is it not persisted to database? Hope someone can help with this.
Here's my code (trying to create everything from codebehind and add them to placeholders on the page just for testing purpose before I move everything to web part):
public partial class Test : System.Web.UI.Page
{
private EntityDataSource eds = new EntityDataSource();
public DetailsView dtlview = new DetailsView();
protected void Page_Load(object sender, EventArgs e)
{
//Initialize Datasource
eds.ConnectionString = "name=DBEntities";
eds.DefaultContainerName = "DBEntities";
eds.EnableDelete = true;
eds.EnableFlattening = false;
eds.EnableInsert = true;
eds.EnableUpdate = true;
eds.EntitySetName = "EmailAccounts";
Controls.Add(eds);//I don't know if this is necessary
//Create DetailsView and configure for inserting on default
dtlview.DataSource = eds;
dtlview.AutoGenerateInsertButton = true;
dtlview.AutoGenerateDeleteButton = true;
dtlview.AutoGenerateEditButton = true;
dtlview.AutoGenerateRows = false;
dtlview.DefaultMode = DetailsViewMode.Insert;
dtlview.AllowPaging = true;
dtlview.DataKeyNames = new string[] { "ID" };
dtlview.AllowPaging = true;
//Create fields since autogeneraterows is false
BoundField bfID = new BoundField();
bfID.DataField = "ID";
bfID.HeaderText = "ID:";
BoundField bfUserID = new BoundField();
bfUserID.DataField = "UserID";
bfUserID.HeaderText = "User ID:";
BoundField bfDisplayName = new BoundField();
bfDisplayName.DataField = "DisplayName";
bfDisplayName.HeaderText = "Display Name:";
BoundField bfEmailAddress = new BoundField();
bfEmailAddress.DataField = "EmailAddress";
bfEmailAddress.HeaderText = "Email:";
BoundField bfPassword = new BoundField();
bfPassword.DataField = "Password";
bfPassword.HeaderText = "Password:";
BoundField bfOutgoingServer = new BoundField();
bfOutgoingServer.DataField = "OutgoingServer";
bfOutgoingServer.HeaderText = "Outgoing server:";
BoundField bfIncomingServer = new BoundField();
bfIncomingServer.DataField = "IncomingServer";
bfIncomingServer.HeaderText = "Incoming Server:";
CheckBoxField chkfIsDefault = new CheckBoxField();
chkfIsDefault.DataField = "IsDefault";
chkfIsDefault.HeaderText = "Is Default?";
dtlview.Fields.Add(bfID);
dtlview.Fields.Add(bfUserID);
dtlview.Fields.Add(bfDisplayName);
dtlview.Fields.Add(bfEmailAddress);
dtlview.Fields.Add(bfPassword);
dtlview.Fields.Add(bfOutgoingServer);
dtlview.Fields.Add(bfIncomingServer);
dtlview.Fields.Add(chkfIsDefault);
dtlview.DataBind();
//Events handling for detailsview
dtlview.ItemInserting += dtlview_ItemInserting;
dtlview.ItemInserted += dtlview_ItemInserted;
dtlview.ModeChanging += dtlview_ModeChanging;
//Add controls to place holder
PlaceHolder2.Controls.Add(dtlview);
}
protected void dtlview_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
e.Values["UserID"] = GetCurrentUserID();
}
protected void dtlview_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
}
protected void dtlview_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
dtlview.ChangeMode(e.NewMode);
if (e.NewMode != DetailsViewMode.Insert)
{
dtlview.DataSource = eds;
dtlview.DataBind();
}
}
}
I think what you have to do is add :
OnContextCreating="XXXXDatasource_OnContextCreating"
OnContextDisposing="XXXXDatasource_OnContextDisposing"
To your EntityDataSource.
Then in you code :
protected void XXXXDatasource_OnContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
e.Context = DBEntities.Entities;
}
protected void XXXXDatasource_OnContextDisposing(object sender, EntityDataSourceContextDisposingEventArgs e)
{
e.Cancel = true;
}
That way, your ObjectContext is correctly set to the EntityDataSource used by your DetailsView.
At least that's what I read as best practice (also look up one object context per page request)

ASP.NET lisbox - Selected first item, always

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.

Resources