How to set dropdownlist values to datatable - asp.net

There is a list of items in drop-down list.I want to add those items in data table while selecting one by one item.How to do that? here i am giving my code.
foreach (System.Web.UI.WebControls.DropDownList li in ddlAssignedTo.Items)
{
if (li.SelectedItem ==checked)
{
DataRow drUsers = dtAssigners.NewRow();
drUsers["GIMID"] = GIMID;
drUsers["MODE"] = 'I';
drUsers["UserId"] = Convert.ToInt32(li.SelectedValue);
drUsers["CreatedBy"] = CurUsr.UserId;
dtAssigners.Rows.Add(drUsers);
}
}
i am getting error near (li.SelectedItem ==checked)... can anyone help me?

Example, if your drop down is like following:
You want to add first item in your table. You can do like:
if (ddl.SelectedValue == "1")
{
//Write Your Code here
}
All these conditions will work using above DropDownList
if(ddl.SelectedValue == "1")
if(ddl.SelectedIndex == 0)
if (ddl.SelectedItem.Text == "One";

You don't need to iterate the items in a dropdown to find the selected item.
var item = ddlAssignedTo.SelectedItem;
if (item != null)
{
DataRow drUsers = dtAssigners.NewRow();
drUsers["GIMID"] = GIMID;
drUsers["MODE"] = 'I';
drUsers["UserId"] = Convert.ToInt32(item.Value);
drUsers["CreatedBy"] = CurUsr.UserId;
dtAssigners.Rows.Add(drUsers);
}
Edit: ok, if multiple items are selected, you can try this -
foreach (ListItem item in ddlAssignedTo.Items)
{
if (item.Selected)
{
}
}
Edit 2: if your drop down list has checkboxes, you are most likely using the checkboxlist control.
The following code works fine for me. Please compare how you are setting up your data table.
DataTable dt = new DataTable("table1");
dt.Columns.Add("col1");
foreach(ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
names.Add(item.Text);
DataRow dr = dt.NewRow();
dr["col1"] = item.Text;
dt.Rows.Add(dr);
}
}

Related

inner join on multiple tables in a DataSet

I have a data set which has 2 data tables.Both these tables are retrieved from 2 distinct Oracle Databases (physically and logically separate).
I need to do a Inner Join on these two tables which reside in 1 dataset. And then display the result in a gridview.
Are there any possibilities of doing SQL Joins on tables inside a Dataset?
If yes, does anyone have a worked out example? If not, can someone point me in the right direction - I do not wish to do any "hacks" (manually looping thru and other iterations of that sorts) as I believe there will be a way to do it within the environment, just need the right approach.
This is in VB .net so would appreciate a more relevant code BUT any help is highly appreciated.
Try this method helper:
private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
DataTable result = new DataTable();
foreach (DataColumn col in t1.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataColumn col in t2.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataRow row1 in t1.Rows)
{
var joinRows = t2.AsEnumerable().Where(row2 =>
{
foreach (var parameter in joinOn)
{
if (!parameter(row1, row2)) return false;
}
return true;
});
foreach (DataRow fromRow in joinRows)
{
DataRow insertRow = result.NewRow();
foreach (DataColumn col1 in t1.Columns)
{
insertRow[col1.ColumnName] = row1[col1.ColumnName];
}
foreach (DataColumn col2 in t2.Columns)
{
insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
}
result.Rows.Add(insertRow);
}
}
return result;
}

CheckBoxList '.Selected' is returning false in every situation

I am trying to grab multiple values from a checkboxlist and add them to a list, But checked values are always false even though the list contains appropriate count value.
code to populate:
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
code for adding to list:
List<int> locList = new List<int>();
for (int x = 0; x < locCkBox.Items.Count; x++){
if(locCkBox.Items[x].Selected){
locList.Add(int.Parse(locCkBox.Items[x].Value));
}
}
The problem I am having is that I cannot get into items.selected
my value is always false.
I have tried populating the checkboxes from postback but i get the same result. My list gives me the appropriate .Count amount of values, but items.selected = false?
I have tried a foreach loop to add to list as well but I get the same results over and over. Am i missing an event or something?
I'm going to take a guess here and say that your code that does the population stuff is being called in the pageload event, so you have something like the following.
private void Page_Load()
{
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
}
If that's the case then your effectively writing over the postback data on each request. To sort this out you need to only perform the databinding when its not a postback, so you need to change the above code to
private void Page_Load()
{
if (!IsPostBack)
{
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
HelpingOthersEntities helpData = new HelpingOthersEntities();
List<LookupStoreLocationsByUserName> theDataSet = helpData.LookupStoreLocationsByUserName(userGuid).ToList<LookupStoreLocationsByUserName>();
locCkBox.DataSource = theDataSet;
locCkBox.DataTextField = "slAddress";
locCkBox.DataValueField = "storeLocationID";
locCkBox.DataBind();
}
}
You should then be able to test the Selected property of the items. I'd also probably change the code your using to test for the selected to something like
List<int> locList = new List<int>();
foreach(var item in locCkBox.Items)
{
if(item.Selected)
{
locList.Add(int.Parse(item.Value));
}
}
or if your on a .NET version with LINQ available
List<int> locList = new List<int>();
(from item in locCkBox.Items where item.Selected == true select item).ForEach(i => locList.Add(i.Value));
Make sure while binding the checkboxlist in page load you have set this check.
if (!Page.IsPostBack)
{
...bind your data
}
This should do the trick.

Find if selected Checkboxes in repeater is of which gender

I have a repeater where I have a column with checkboxes and one column with gender which i populate with database value.
I want to find out if user has selected multiple checkboxes of same gender e.g. male if so do something otherwise If a user selects multiple checkboxes with a mixture of male and female then do something else.
so far I was thinking to add this to a list and then see if list has same values but not sure if it is best idea here is my code (I have a hidden field to get gender ), I am running this on click event of a button:
foreach (RepeaterItem rptItem in myrepeater.Items)
{
hiddenGender = rptItem.FindControl("hiddenGender") as HiddenField;
if (Convert.ToInt32(hiddenGender.Value) == 0)
{
gender.Add(0);
}
else if (Convert.ToInt32(hiddenGender.Value) == 1)
{
gender.Add(1);
}
else if (Convert.ToInt32(hiddenGender.Value) == 2)
{
gender.Add(2);
}
}
ps without usage of linq as it is framework 2.0
I'm not sure if i understand what you want to do, but if i do, this code does the same:
foreach (RepeaterItem rptItem in myrepeater.Items)
{
hiddenGender = rptItem.FindControl("hiddenGender") as HiddenField;
gender.Add(Convert.ToInt32(hiddenGender.Value));
}
got it, here is the code to maybe help others(first I get the first item and see if it matches next item) :
public static bool ListEquality(IEnumerable<int> lstGender)
{
int? first = null;
bool isUnique = true;
foreach (var item in lstGender)
{
if (first == null)
{
first = item;
}
else if (first.Value != item)
{
isUnique = false;
}
}
return isUnique;
}

Dynamic Template Controls

On !PostBack dynamic templates are created based on the number of rows needed for check boxes. The control id's are chkbox_id. I am unable to retrieve the dynamic check boxes via the following code and NullReferenceException is always thrown.
The code before loops through the gridview rows, then datatable dt references the possible number of dynamic columns.
for (int i = 0; i < dt.Rows.Count; i++)
{
string id = dt.Rows[i]["id"].ToString();
CheckBox cb = (CheckBox)row.FindControl("ckbox_" + id);
if (cb.Checked)
{ // do things }
}
Checkboxes defined here within page load:
if (!Page.IsPostBack)
{
foreach (DataRow dRow in dt.Rows)
{
TemplateField ckhColumn = new TemplateField();
ckhColumn.HeaderTemplate = new GridViewTemplate(ListItemType.Header, dRow["name"].ToString());
ckhColumn.ItemTemplate = new GridViewTemplate(ListItemType.Item, "ckbox_" + dRow["id"].ToString());
gvProductPriceList.Columns.Add(ckhColumn);
}
}
Let me know if I need to clarify anything else.
I'm not positive on this, and I don't have a minute to try it, but it might work if you do a row.Parent.FindControl(...). Also, if you use the as operator instead of a direct cast, you won't have the null reference exception (i.e. you can check for it):
CheckBox cb = row.Parent.FindControl("ckbox_" + id) as CheckBox;
if (cb != null)
{
// ...
}

Return ASP DDL or Telerik control

I'm trying to write a more generic method that will populate either an ASP.NET dropdownlist OR a telerik RadComboBox with states. I'd like to pass the control in as a parameter to the method. I have a DataTable that holds all the states, which I loop through (see below) - I'd like to make this applicable to a Telerik RadComboBox - so I need to change the first parameter, and also the part where I Insert a new ListItem - for Telerik RadComboBox it is new RadComboBoxItem. How can I do this?
public void PopulateStates(DropDownList ddlStates, string country)
{
ddlStates.Items.Clear();
DataLookup dl = new DataLookup();
DataTable dt = dl.GetStatesByCountry(country);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
ddlStates.Items.Insert(0, new ListItem(""));
for (int i = 0; i < dt.Rows.Count; i++)
{
ddlStates.Items.Add(new ListItem(dt.Rows[i]["STCD_Descr"].ToString(),
dt.Rows[i]["STCD_State_CD"].ToString()));
}
}
}
}
I looked up the telerik documentation & there doesn't seem to be common way of doing - what you are trying to do.
If it is possible, try using the databinding (setting the DataSource & calling DataBind).
Note: I haven't tried it. But I think that should be supported by both.
Since ListBox and RadComboBox does not have common classes except for the "Control" class you will need to check the actual type.
How about the following code?
public void PopulateStates(Control ddl, string country)
{
object listItem = new object();
switch (ddl.GetType().Name)
{
case "RadComboBox":
listItem = listItem as RadComboBoxItem;
ddl = ddl as RadComboBox;
break;
case "ListBox":
listItem = listItem as ListItem;
ddl = ddl as ListBox;
break;
default:
return;
}
// proceed with your code
}

Resources