I am working on exporting data and right now some fields export the value, instead of the text. So I am saving the object that returns the text and value to a list box and matching it to the value in the listbox from the object like so:
MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataBind();
string materialString = "";
foreach (ListItem i in listBoxMaterials.Items)
{
if (i.Value == row["MaterialTypeID"].ToString())
{
materialString = i.Text;
}
}
When I use this for the i.Value it always returns "System.Data.DataRowView" instead of the actual value. I'm doing this all in code behind. Anyway around this to get it to work?
Thanks!
You need to set the DataTextField and DataValueField properties of the DropDownList. Example:
MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataTextField = "MaterialName";
listBoxMaterials.DataTextValue = "MaterialID";
listBoxMaterials.DataBind();
string materialString = "";
foreach (ListItem i in listBoxMaterials.Items)
{
if (i.Value == row["MaterialTypeID"].ToString())
{
materialString = i.Text;
}
}
Related
How can you set default value for combobox provided you get the value from table in database. I am thinking comparing the value with column [2]/destinationColumn to see which value in the table should be selected as default. This is my code so far which is wrong. Suggestion or an example code will be much appreciated. Thank you in advance guys.
string sqlLookupColumn = "SELECT LookUpColumnID, SOURCE_NAME FROM TB_LOOKUP_COLUMN ORDER BY SOURCE_NAME ASC";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxColumn dgvCboColumn = new DataGridViewComboBoxColumn();
dgvCboColumn.Name = "DESTINATION_NAME";
dataGridView1.Columns.Add(dgvCboColumn);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewComboBoxCell cboDestinationColumns = (DataGridViewComboBoxCell)(row.Cells[3]);
cboDestinationColumns.DataSource = dsColumn.Tables[0];
string destinationColumn = row.Cells[2].Value.ToString();
cboDestinationColumns.DisplayMember = "SOURCE_NAME";
cboDestinationColumns.ValueMember = "LookUpColumnID";
if (destinationColumn == cboDestinationColumns.DisplayMember)
{
cboDestinationColumns.Selected = true;
}
}
Things that i can see wrong
1- Your loop on the GridView wont work, do the loop on the Dataset instead of the Gridview...
2- You are comparing destinationColumn with cboDestinationColumns.DisplayMember which = "SOURCE_NAME" and you want If destinationColumn = "InvoiceNo"
3- Add the to the combo items using for loop and .add method, and do your if statement their.
To add the items:
1st add this class
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
Then loop on the Dataset
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
DataRow dr = ds.Tables[0].Rows[i];
ComboboxItem tmp= new ComboboxItem();
tmp.Text = dr["SOURCE_NAME"];
tmp.Value = dr["LookUpColumnID"];
cb.Items.Add(tmp);
if(dr["InvoiceNo"].ToString() =="")//Your condition here to set selected
cb.SelectedIndex = i;
}
I think I am overseeing something.
I dynamically generate a few ComboBoxes with this code (I do the same for other controls like TextBox, Label etc)
private ComboBox addControlsComboBox(string Id, string TBName, int point_X, int point_Y, int SizeWidth, DataTable DT)
{
ComboBox combobox = new ComboBox();
combobox.Text = TBName;
combobox.Location = new Point(point_X, point_Y);
combobox.Size = new Size(SizeWidth, 20);
combobox.Name = Id + TBName;
combobox.DataSource = DT;
combobox.DisplayMember = "key";
combobox.ValueMember = "value";
combobox.Enabled = true;
return combobox;
}
When I automatically want to set the selected value, for the controls all the values are set correct except for the ComboBox. Not 1 comboBox is updated but all the ComboBoxes.
I use a nested dictionary object to store all the values that i need to match.
See part of the used update Code
foreach (Control gb in GroupPanel.Controls)
{
foreach (Control childc in gb.Controls)
{
if (DataCollection[GroupNames].ContainsKey(childc.Name))
{
KeyName = childc.Name;
numberLessKeyName = SL.RemoveDigits(childc.Name);
TextValue = DataCollection[GroupNames][KeyName];
switch (NumberLessKeyName)
{
case "Name":
int IntTextValue = Convert.ToInt32(TextValue);
TextValue = IntTextValue.ToString("d2");
break;
}
switch (childc.GetType().ToString())
{
case "System.Windows.Forms.TextBox":
childc.Text = TextValue;
break;
case "System.Windows.Forms.ComboBox":
// Not Working
ComboBox combobox = (ComboBox)childc;
combobox.SelectedValue = TextValue;
//Also not Working
// --> childc.Text = TextValue;
break;
case "System.Windows.Forms.CheckBox":
CheckBox chChildc = (CheckBox)childc;
if (TextValue == "Yes")
{
chChildc.Checked = true;
}
break;
};
}
}
}
What I am doing wrong?
Can somebody help me please?
[EDIT 1]
Thanks to Karol
I added The Following Lines + interface ICloneable and it worked. Many Thanks.
DataTable DT = new DataTable();
DT = DTAttribute;
DataTable DTClone = (DataTable)DT.Clone();
For those searching [C# Object Clone Wars][1] link
[EDIT 2]
A other Idea is to use COPY (works also)
DataTable DT = new DataTable();
DT = DTAttribute;
DataTable DTClone = DT.Copy();
I think You bind all ComboBox same DataTable.
You must have diffrent instance of DataTable for each ComboBox. You can do this in two ways:
- Once again SELECT data from database.
- Use deep copy to make new instance of DataTable.
Code:
DataSet ds = _dalEquipmentwiseCheckList.getEquipmentName();
ddEquipmentName.DataSource = ds.Tables[0].DefaultView;
ddEquipmentName.DataTextField = ds.Tables[0].Columns[1].ToString();
ddEquipmentName.DataValueField = ds.Tables[0].Columns[0].ToString();
ddEquipmentName.DataBind();
What I want is: when selecting a row in the GridView, the corresponding equipment name
should get selected in the dropdown list:
var selectRow = MyGridView.SelectedRow;
ddEquipmentName.SelectedValue = selectRow.Cells[2].Text;
****//this is giving me error****
Selected value does not work in this way. Try this:
ddEquipmentName.SelectedIndex = ddEquipmentName.Items.IndexOf(ddEquipmentName.Items.FindByText(selectRow.Cells[2].Text));
You can try :
GridViewRow selectRow = MyGridView.SelectedRow;
ddEquipmentName.selectedItem.Text = selectRow.Cells[2].Text;
void setDataContext()
{
var selectRow = GridEquipmentChechList.MyGridView.SelectedRow;
if (selectRow != null)
{
txtECNumber.Text = selectRow.Cells[1].Text;
**ddEquipmentName.SelectedIndex = ddEquipmentName.Items.IndexOf(ddEquipmentName.Items.FindByText(selectRow.Cells[2].Text));**
**ddDescription.SelectedIndex = ddDescription.Items.IndexOf(ddDescription.Items.FindByText(selectRow.Cells[3].Text));**
}
}
I create one datalayer method
public static List<SegmentBL> GetAllSegment(string SortDirection, string SortExpression)
{
var ds = DBHelper.GetDatabase().ExecuteDataSet("UDS_Select_SegmentMaster");
var val = ds.Tables[0].AsEnumerable().Select(r => new SegmentBL
{
_SegmentId = Convert.ToInt32(r[0].ToString()),
_SegmentName = r[1].ToString()
});
List<SegmentBL> list = val.ToList();
return list;
}
from that I create one Bussiness logic method
public DropDownList GetAll(string SortDirection, string SortExpression)
{
var list = new DropDownList();
list.DataSource = SegmentDL.GetAllSegment(SortDirection, SortExpression);
list.DataTextField = "_SegmentName";
list.DataValueField = "_SegmentID";
list.DataBind();
ListItem item = new ListItem();
item.Text = "--Select--";
item.Value = "0";
list.Items.Insert(0, item);
return list;
}
Finally Presentation Layer Method for filling dropdownlist
private void FillSegment()
{
ddlSegment.DataSource = seg.GetAll(General.SortAscending,"SegmentID").Items;
ddlSegment.DataBind();
ddlSegment.DataTextField = "_SegmentName";
ddlSegment.DataValueField = "_SegmentID";
}
It's working fine except the DataTextField and DataValueField not assign properly. Currently DataTextField and DataValueField same. What is mistake I did in above code.
You are binding before the elements are added to the datasource bind after the elements being added. You may pass dropdownlist to your method intead of creating local drop down in GetAll method.
public DropDownList GetAll(string SortDirection, string SortExpression, DropDownList list)
{
// var list = new DropDownList(); //Remove this line
list.DataSource = SegmentDL.GetAllSegment(SortDirection, SortExpression);
list.DataTextField = "_SegmentName";
list.DataValueField = "_SegmentID";
ListItem item = new ListItem();
item.Text = "--Select--";
item.Value = "0";
list.Items.Insert(0, item);
list.DataBind();
return list;
}
Move the Databind() line.
private void FillSegment()
{
ddlSegment.DataSource = seg.GetAll(General.SortAscending,"SegmentID").Items;
ddlSegment.DataTextField = "_SegmentName";
ddlSegment.DataValueField = "_SegmentID";
ddlSegment.DataBind(); //After and not before defining the fields value
}
I have a combobox with objects of Foo type, here is the Foo class:
public class Foo
{
public string name { get; set; }
public string path { get; set; }
}
The Foo.name is the displayed text in the combobox and Foo.path is the value of the selected option.
I want to delete an option from the combobox after some operation I made.
I've tried these ways:
1
comboBox2.Items.Remove(#comboBox2.Text);
2
comboBox2.Items.Remove(#comboBox2.SelectedValue.ToString());
3
Foo ToDelete = new Foo();
ToDelete.name = #comboBox2.Text;
ToDelete.path = #comboBox2.SelectedValue.ToString();
comboBox2.Items.Remove(ToDelete);
Nothing works for me. : / How to do this?
UPDATE
This is how I'm initializing my combobox:
string[] filePaths = Directory.GetFiles(sites.paths[comboBox1.SelectedIndex]);
List<Foo> combo2data = new List<Foo>();
foreach (string s in filePaths)
{
Foo fileInsert = new Foo();
fileInsert.path = s;
fileInsert.name = Path.GetFileName(s);
combo2data.Add(fileInsert);
}
comboBox2.DataSource = combo2data;
comboBox2.ValueMember = "path";
comboBox2.DisplayMember = "name";
comboBox2.Items.Remove(comboBox2.SelectedValue); will only remove from the combobox, not from the datasource bound to the combobox. You may remove it from the datasource and re-bind the datasource.
Use ComboBox.SelectedIndex property.
For example: let me have comboBox1 added to the form. In the delete button:
if (comboBox1.SelectedIndex >= 0)
comboBox1.Items.RemoveAt(comboBox1.SelectedIndex);
combox1.Remove(takes an object)
Object selectedItem = comboBox1.SelectedItem;
So you cna do it this way combox1.Remove(selectedItem);
Suppose you want to Remove Items by Index:
combo2data.RemoveAt(0); //Removing by Index from the dataSource which is a List
//Rebind
comboBox2.DataSource = null;
comboBox2.DataSource = combo2data;
comboBox2.ValueMember = "path";
comboBox2.DisplayMember = "name";
Suppose you want to Remove by seraching for a member value
Foo item = combo2data.Where(f => f.name.Equals("Tom")).FirstOrDefault();
if (item != null)
{
combo2data.Remove(item);
comboBox2.DataSource = null;
comboBox2.DataSource = combo2data;
comboBox2.ValueMember = "path";
comboBox2.DisplayMember = "name";
}
These 2 commands will remove an item from your data source.
list.Remove((Foo)comboBox1.SelectedItem);
or
list.Remove(list.Find(P=>P.name == comboBox1.SelectedText));
I think the secret is to first attribute null to the datasource and after rebind to a modified collection:
int idToRemove = 1;
var items = (cbx.DataSource as List<MyEntity>);
items.RemoveAll(v => v.Id == idToRemove);
rebindCombobox(cbx, items, "Name", "Id");
private void rebindCombobox(ComboBox cbx, IEnumerable<Object> items, String displayMember, String valueMember)
{
cbx.DataSource = null;
cbx.DisplayMember = displayMember;
cbx.ValueMember = valueMember;
cbx.DataSource = items;
}
Perhaps delete all items in the Combobox with
comboBox.Items.Clear();