For the life of me I I don't seem to be able to get Databinding to Dynamics or ExpandoObjects working.
I have tried this in WinForms and in WebForms and get different results in each:
In ASP.NET:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
dynamic contacts = new List<dynamic>();
contacts.Add(new ExpandoObject());
contacts[0].Name = "Patrick Hines";
contacts[0].Phone = "206-555-0144";
contacts.Add(new ExpandoObject());
contacts[1].Name = "Ellen Adams";
contacts[1].Phone = "206-555-0155";
DropDownList1.DataSource = contacts;
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
}
This results in:
DataBinding: 'System.Dynamic.ExpandoObject' does not contain a property with the name 'Name'.
In WinForms, I have a different issue:
dynamic contacts = new List<dynamic>();
contacts.Add(new ExpandoObject());
contacts[0].Name = "Patrick Hines";
contacts[0].Phone = "206-555-0144";
contacts.Add(new ExpandoObject());
contacts[1].Name = "Ellen Adams";
contacts[1].Phone = "206-555-0155";
this.departmentList.DataSource = contacts;
this.departmentList.DisplayMember = "Name";
This results in the ComboBox displaying "System.Dynamic.ExpandoObject" - as it is just calling ToString() on the two items in the collection. :(
I appreciate the help!
Try this
var contacts = new List<dynamic>()
{
new {Name = "Patrick Hines",Phone = "206-555-0144"},
new {Name = "Ellen Adams",Phone = "206-555-0155"}
};
Related
This question already has answers here:
How to bind LINQ data to dropdownlist
(3 answers)
Closed 8 years ago.
can someone help me
Im having issues binding my dropdown list from my sql linq query, theres seems to be issues with anon types not being statically typed and then the list is not being populated
please help thanks
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
//List<Location> thelocations = new List<Location>();
var locations = new[] { from a in dc.Locations select new { a.name } };
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataTextField = "Location";
ddLocation.DataValueField = "Location";
}
Try it:
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
var locations = from a in dc.Locations;
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations.ToList();
ddLocation.DataTextField = "name";
ddLocation.DataValueField = "Id";
ddLocation.DataBind();
}
I hope it will help you.
Try this, You have missed ddLocation.DataBind(); and did't add this dynamic DDL to any Controls and needs to be some changes
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
List<Location> locations = (from a in dc.Locations).ToList();
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataTextField = "name";
ddLocation.DataValueField = "Id";
ddLocation.DataBind();
divRunServer.Controls.Add(ddLocation);
}
add this div tag in client side
<div id="divRunServer" runat="server"></div>
Another way:
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext("name = name");
var locations = from a in dc.Locations select new {a1 = a.Id, a2 = a.name };
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "a1";
ddLocation.DataTextField = "a2";
}
Anonymous types should work fine, you just provided property names for DataTextField and DataValueField that aren't in your anonymous type. Try:
V-- give the property a name
var locations = from a in dc.Locations select new { Location = a.name };
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataTextField = "Location";
ddLocation.DataValueField = "Location";
However I notice you're not doing anything with the DropDownList that you create - you may be unintentionally hiding a page control named ddLocation.
I bind the gridview in the following event:(subjectdropdown_SelectedIndexChanged)
I send the gridview in the following event as a parameter to another method:Button1_click event.
protected void subjectdropdown_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable getmarkfdb = inter.getmarksfromdatabaseothers(comp);
if (getmarkfdb.Rows.Count > 0)
{
TemplateField lable1 = new TemplateField();
lable1.ShowHeader = true;
lable1.HeaderText = "AdmissionNumber";
lable1.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "AdmissionNumber", "AdmissionNumber", "Label");
studmarkgrid.Columns.Add(lable1);
TemplateField label2 = new TemplateField();
label2.ShowHeader = true;
label2.HeaderText = "RollNumber";
label2.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "RollNumber", "RollNumber", "Label");
studmarkgrid.Columns.Add(label2);
TemplateField label3 = new TemplateField();
label3.ShowHeader = true;
label3.HeaderText = "Name";
label3.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "Name", "Name", "Label");
studmarkgrid.Columns.Add(label3);
TemplateField extmep = new TemplateField();
extmep.ShowHeader = true;
extmep.HeaderText = "ExternalMark";
extmep.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "ExternalMark", "ExternalMark", "TextBox");
studmarkgrid.Columns.Add(extmep);
studmarkgrid.DataSource = getmarkfdb;
studmarkgrid.DataBind();
}
}
In the TextBoxTemplate column of the gridview I fill the Mark for student and in the following event i send the gridview to insertstumark method for read data from gridview and save into database. but in the insertstumark method gridview rows data are null.
protected void Button1_Click(object sender, EventArgs e)
{
comp.ACADAMICYEAR = acyeardropdown.SelectedItem.Text;
comp.MEDIUM = mediumdropdown.SelectedItem.Text;
string clas = classdropdown.SelectedItem.Text;
string[] cs = clas.Split('-');
comp.CLASSNAME = cs[0].ToString();
comp.SECTIONNAME =Convert.ToChar(cs[1].Trim().ToString());
comp.EXAMNAMES = examnamedropdown.SelectedItem.Text;
comp.SUBJECTID = subjectdropdown.SelectedValue.ToString();
// studmarkgrid.DataBind();
// System.Web.UI.WebControls.GridView grid = studmarkgrid;
// System.Web.UI.WebControls.GridView grid = ViewState["stdmarkgrid"] as System.Web.UI.WebControls.GridView;
DataTable studtable = null;
// System.Web.UI.WebControls.GridView grid = (System.Web.UI.WebControls.GridView)ViewState["stdmarkgrid"];
bool studm = inter.inserstumark(comp,stumarkgrid);
}
What is the problem. I tried to stored the gridview in viewstate. but in the following line it through the error. How to solve this problem?
System.Web.UI.WebControls.GridView grid = ViewState["stdmarkgrid"] as System.Web.UI.WebControls.GridView;
A lot of times, if the data is bound to the GridView too late in the Page Lifecycle, the GridView is rendered, and the data forgotten, so at the next PostBack, you won't have access to the GridView's underlying data source.
That looks like what's happening here. Just save the result of getmarksfromdatabaseothers to ViewState so you can access it again as necessary.
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)
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;
This is my third time asking this question. I am not getting good answers regarding this. I wish I could get some help but I will keep asking this question because its a good question and SO experts should not ignore this...
So I have about 10 dropdownlist controls that I add manually in the DetailsView control manually like follows. I should be able to add this programmatically. Please help and do not ignore...
<asp:DetailsView ID="dvProfile" runat="server"
AutoGenerateRows="False" DataKeyNames="memberid" DataSourceID="SqlDataSource1"
OnPreRender = "_onprerender"
Height="50px" onm="" Width="125px">
<Fields>
<asp:TemplateField HeaderText="Your Gender">
<EditItemTemplate>
<asp:DropDownList ID="ddlGender" runat="server"
DataSourceid="ddlDAGender"
DataTextField="Gender" DataValueField="GenderID"
SelectedValue='<%#Bind("GenderID") %>'
>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate >
<asp:Label Runat="server" Text='<%# Bind("Gender") %>' ID="lblGender"></asp:Label>
</ItemTemplate>
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
=======================================================
Added on 5/3/09
This is what I have so far and I still can not add the drop down list programmatically.
private void PopulateItemTemplate(string luControl)
{
SqlDataSource ds = new SqlDataSource();
ds = (SqlDataSource)FindControl("ddlDAGender");
DataView dvw = new DataView();
DataSourceSelectArguments args = new DataSourceSelectArguments();
dvw = (DataView)ds.Select(args);
DataTable dt = dvw.ToTable();
DetailsView dv = (DetailsView)LoginView2.FindControl("dvProfile");
TemplateField tf = new TemplateField();
tf.HeaderText = "Your Gender";
tf.ItemTemplate = new ProfileItemTemplate("Gender", ListItemType.Item);
tf.EditItemTemplate = new ProfileItemTemplate("Gender", ListItemType.EditItem);
dv.Fields.Add(tf);
}
public class ProfileItemTemplate : ITemplate
{
private string ctlName;
ListItemType _lit;
private string _strDDLName;
private string _strDVField;
private string _strDTField;
private string _strSelectedID;
private DataTable _dt;
public ProfileItemTemplate(string strDDLName,
string strDVField,
string strDTField,
DataTable dt
)
{
_dt = dt;
_strDDLName = strDDLName;
_strDVField = strDVField;
_strDTField = strDTField;
}
public ProfileItemTemplate(string strDDLName,
string strDVField,
string strDTField,
string strSelectedID,
DataTable dt
)
{
_dt = dt;
_strDDLName = strDDLName;
_strDVField = strDVField;
_strDTField = strDTField;
_strSelectedID = strSelectedID;
}
public ProfileItemTemplate(string ControlName, ListItemType lit)
{
ctlName = ControlName;
_lit = lit;
}
public void InstantiateIn(Control container)
{
switch(_lit)
{
case ListItemType.Item :
Label lbl = new Label();
lbl.DataBinding += new EventHandler(this.ddl_DataBinding_item);
container.Controls.Add(lbl);
break;
case ListItemType.EditItem :
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(this.lbl_DataBinding);
container.Controls.Add(ddl);
break;
}
}
private void ddl_DataBinding_item(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ddl.ID = _strDDLName;
ddl.DataSource = _dt;
ddl.DataValueField = _strDVField;
ddl.DataTextField = _strDVField;
}
private void lbl_DataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
lbl.ID = "lblGender";
DropDownList ddl = (DropDownList)sender;
ddl.ID = _strDDLName;
ddl.DataSource = _dt;
ddl.DataValueField = _strDVField;
ddl.DataTextField = _strDTField;
for (int i = 0; i < _dt.Rows.Count; i++)
{
if (_strSelectedID == _dt.Rows[i][_strDVField].ToString())
{
ddl.SelectedIndex = i;
}
}
lbl.Text = ddl.SelectedValue;
}
}
I found this article http://aspalliance.com/1125 about progrmatically creating template field. I hope this can be helpful to solve this problem.
What have you tried? What problem are you having? If you haven't answered these questions before, then it's no surprise that you haven't received a good answer.
Obviously, you have to locate the TemplateFields for which you want to add dropdowns, and you have to set their EditItemTemplate property to an instance of a class that implements ITemplate. That instance will have it's InstantiateIn method called to add controls to a parent control. In this case, this is where you would configure and add your DropDownList.
If this description is not adequate, then you'll have to say in what way it's not adequate, so that I or someone else can answer.