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.
Related
I have a dropdownlist with few items which bind in code behind. I populate dropdownlist from below query.
Select ID, Name, IsGroup from TempTable
i set DataTextField = "Name" and DataValueField = "ID"
Now i want to disable some items based on "IsGroup" value in DataBound event. How can i access this "IsGroup" column.
For Each item As ListItem In dd.Items
If (What i will compare here = "N") Then
item.Attributes.Add("disabled", "disabled")
End If
Next
Regards
protected void Page_Load(object sender, EventArgs e)
{
var data = GetData();
List<ListItem> items = new List<ListItem>();
foreach (DataRow row in data.Rows)
{
var item = new ListItem()
{
Value = row["Id"].ToString(),
Text = row["Name"].ToString()
};
if (row["IsGroup"].ToString() != "N")
{
item.Attributes.Add("disabled", "disabled");
}
items.Add(item);
}
this.DropDownList1.Items.AddRange(items.ToArray());
}
ref: make drop down list item unselectable
You are doing 2 activities
Fetching data from the database
populating the list item and attaching property/properties to the list item element
Method 1 : Primarily to understand the different operations involved.
class SurroundingClass
{
class Example1
{
public int ID { get; set; }
public string Name { get; set; }
public string IsGroup { get; set; }
}
public void PopulateExample1()
{
// Separate Sections for Database and Dropdown Manipulation
// Database operation
var cs = System.Configuration.ConfigurationManager.ConnectionStrings("CS").ConnectionString;
string sql = "Select ID, Name, IsGroup from TempTable";
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, conn);
var dr = cmd.ExecuteReader();
List<Example1> e1 = new List<Example1>();
while (dr.Read)
{
var e = new Example1();
e.ID = dr.GetInt32(0);
e.Name = dr.GetString(1);
e.IsGroup = dr.GetString(2);
e1.Add(e);
}
dr.Close();
conn.Close();
// Populate Dropdown
foreach (var i in e1)
{
var li = new ListItem(i.Name, i.ID);
if (i.IsGroup == "Y")
li.Attributes.Add("disabled", "disabled");
ddlExample1.Items.Add(li);
}
}
}
Method 2 : Squeezing the operations in Method 1 together
public void PopulateExample2()
{
// Database Operation and Dropdown Manipulation together
var cs = System.Configuration.ConfigurationManager.ConnectionStrings("CS").ConnectionString;
string sql = "Select ID, Name, IsGroup from TempTable";
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, conn);
var dr = cmd.ExecuteReader();
while (dr.Read)
{
var li = new ListItem(dr.GetString(1), dr.GetInt32(0));
if (dr.GetString(2) == "Y")
li.Attributes.Add("disabled", "disabled");
ddlExample2.Items.Add(li);
}
dr.Close();
conn.Close();
}
Please note that there can be several variations to the solution, this being only one of them.
I have been given some c# code and have been asked to create a markup (.aspx) file that would go along with it.
I am not asking for help to write the code, but instead, how to go about it.
Here is the code:
public partial class search : Page
{
protected override void OnLoad(EventArgs e)
{
int defaultCategory;
try
{
defaultCategory = Int32.Parse(Request.QueryString["CategoryId"]);
}
catch (Exception ex)
{
defaultCategory = -1;
}
Results.DataSource = GetResults(defaultCategory);
Results.DataBind();
if (!Page.IsPostBack)
{
CategoryList.DataSource = GetCategories();
CategoryList.DataTextField = "Name";
CategoryList.DataValueField = "Id";
CategoryList.DataBind();
CategoryList.Items.Insert(0, new ListItem("All", "-1"));
CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(defaultCategory.ToString()));
base.OnLoad(e);
}
}
private void Search_Click(object sender, EventArgs e)
{
Results.DataSource = GetResults(Convert.ToInt32(CategoryList.SelectedValue));
Results.DataBind();
}
private DataTable GetCategories()
{
if (Cache["AllCategories"] != null)
{
return (DataTable) Cache["AllCategories"];
}
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * From Categories");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
Cache.Insert("AllCategories", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
connection.Dispose();
return dt;
}
private DataTable GetResults(int categoryId)
{
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * FROM Products P INNER JOIN Categories C on P.CategoryId = C.Id WHERE C.Id = {0} OR {0} = -1", categoryId);
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Dispose();
return dt;
}
}
EDIT
In the above code, what is the Results object and is the CategoryList just a listbox?
As Nilesh said this seems like a search page, You can possibly try creating the a Webform using Visual studio which is just drag and drop controls into canvas and that will create the mark up for the controls in the code window.
This code behind seems to be doing the following,
On page load at Get request (when its !Page.IsPostBack) page is going to get categories using GetCategories() and fill the drop down list "CategoryList" with all category names (default selected one being the defaultcategory ID from query string).
The search button takes the dropdown's selected value and calls the GetResults() to get data table to fill the grid view "Results". So you need 3 controls (Dropdown list, Button, Gridview) in the webform with these names..
My dropdownlist is set to databine like this...
dt = dal.FillDataTable(SqlConnectionString, "SELECT SQL Query Statement")
dropdownlist1.datasource = dt
dropdownlist1.datatextfield = dt.columns.item(0).tostring
dropdownlist1.databind()
This is turn populates my dropdownlist, when a user selects a value, it is then populated to the remaining textboxes on the remaining forms with a session call...
dropdownlist2.add(ctype(session.item("valOne"), String))
Through this session it populates the one value, is it possible to display the selected value but also include all other dropdownlist items in case they want to change thier selection? Any suggestions would really help?
I didnt understand adding one value at a time. Just show them all the associated values and let them select or change their decision.
Sample code
public DataSet GetmTest_Filter()
{
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[1];
oParam[0] = new SqlParameter("#col_Id", _scolidvalue);
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "your_stored_procedure_here", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
public void ddlFill_Test(DropDownList ddl)
{
DataSet oDSddlmTest = new DataSet();
oDSddlmTest = GetmTest_Filter();
if (oDSddlmTest.Tables[0].Rows.Count > 0)
{
ddl.DataSource = oDSddlmTest.Tables[0].DefaultView;
ddl.DataTextField = "col_desc";
ddl.DataValueField = "col_id";
ddl.DataBind();
}
else
{
ddl.Enabled = false;
}
}
May this help you.
i created gridview dynamically,
which consists of Textboxes and buttonfield, on row command event of the gridview i want to access the content of textbox.
i am not able to access the textbox
here is my code
protected void FillGridListTollCollection()
{
TollCollectionBLLC tollcollectionBLLC = new TollCollectionBLLC();
dataTable = tollcollectionBLLC.GetTollCollectionDetailsBLLC(187, 1, 1, "10/10/2011");
//put the gridview into the placeholder to get the values of textboxes in gridview
PlaceHolder1.Controls.Add(GridListTollColletion);
foreach (DataColumn col in dataTable.Columns)
{
if (col.ToString() == "TollCollID")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollCollID";
bField.DataField = "TollCollID";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollAmtApplicable")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollAmtApplicable";
bField.DataField = "TollAmtApplicable";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollCollDesc")
{
BoundField bField = new BoundField();
bField.HeaderText = "Transaction Types";
bField.DataField = "TollCollDesc";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "Total")
{
BoundField bField = new BoundField();
bField.HeaderText = "Total";
bField.DataField = "Total";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString().Contains("Rate"))
{
BoundField bField = new BoundField();
bField.HeaderText = col.ToString();
bField.DataField = col.ToString();
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
//Declare the bound field and allocate memory for the bound field.
TemplateField tfield = new TemplateField();
//Initalize the DataField value.
tfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
tfield.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
tfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.ItemStyle.VerticalAlign = VerticalAlign.Middle;
//Initialize the HeaderText field value.
tfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
GridListTollColletion.Columns.Add(tfield);
}
protected void GridListTollColletion_RowCommand(object sender, GridViewCommandEventArgs e)
{
int tempCarCount = 0;
// here i am getting exception
int.TryParse( ( (TextBox)GridListTollColletion.Rows[Convert.ToInt32(e.CommandArgument)].Cells[Convert.ToInt32(e.CommandArgument)].Controls[3]).Text , out tempCarCount);
}
public class GridViewTemplate : ITemplate
{
//A variable to hold the type of ListItemType.
ListItemType _templateType;
//A variable to hold the column name.
string _columnName;
//Constructor where we define the template type and column name.
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;
//Stores the column name.
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label(); //Allocates the new label object.
lbl.Text = _columnName; //Assigns the name of the column in the lable.
container.Controls.Add(lbl); //Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox(); //Allocates the new text box object.
tb1.Width = 60;
tb1.Height = 22;
tb1.MaxLength = 50;
tb1.ID = "v";
//Creates a column with size 4.
tb1.DataBinding += new EventHandler(tb1_DataBinding); //Attaches the data binding event.
tb1.Columns = 7;
container.Controls.Add(tb1);
//Adds the newly created textbox to the container.
break;
case ListItemType.EditItem:
//As, I am not using any EditItem, I didnot added any code here.
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
public IOrderedDictionary ExtractValues(Control container)
{
OrderedDictionary dict = new OrderedDictionary();
if (_templateType == ListItemType.Item)
{ string value = ((TextBox)container.FindControl("tb1" + _columnName)).Text;
dict.Add(_columnName, value); }
return dict;
}
void tb1_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}
public GridViewTemplate()
{
//
// TODO: Add constructor logic here
//
}
}
The template is applied statically. So, you wont be able to access the control as you are trying to do.
Try using -
var textbox = GridListTollColletion.FindControl(<yourtextbox>);
Is it not convenient if you bind these added controls on GridView.RowDataBound event.
Check this BindData to ITemplate for GridView in code behind
If you are following this MSDN Article How To: Create ASP.NET Web Server Control Templates Dynamically to take idea about this then check this code snippet.
static void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
RepeaterItem ri = (RepeaterItem)ph.NamingContainer;
Int32 item1Value = (Int32)DataBinder.Eval(ri.DataItem, "CategoryID");
String item2Value = (String)DataBinder.Eval(ri.DataItem, "CategoryName");
((Label)ph.FindControl("item1")).Text = item1Value.ToString();
((Label)ph.FindControl("item2")).Text = item2Value;
}
It have Item_DataBinding a static method. you are setting up this stuff statically, so check this article to improve your code.
In Edit Template i suggest you to use RowBound Event to handle for these template controls.. there you can easily access them.
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"}
};