I am populating a DataTable with some values (after defining the column names) and then using it as a data source for a Sage Grid - functionally very similar to a WinForms DataGridView.
So far, I have tried adding the data type to the DataTable columns and populating a BindingSource with the DataTable and then binding it to the Sage Grid. When viewing the contents of the DataTable whilst debugging you can see the data is there using DataSet Visualiser.
Creating the DataTable -
DataTable failedOrders = new DataTable();
failedOrders.Columns.Add("externalItemCodeColumn", typeof(String));
failedOrders.Columns.Add("reasonColumn", typeof(String));
foreach (String item in insufficientItemsAvailable)
{
DataRow dataRow = failedOrders.NewRow();
dataRow["externalItemCodeColumn"] = item;
dataRow["reasonColumn"] = "Not enough available items in WAREHOUSE";
failedOrders.Rows.Add(dataRow);
}
Populating the Sage Grid -
Sage.Common.Controls.GridColumn externalItemCodeColumn = new Sage.Common.Controls.GridColumn();
externalItemCodeColumn.Caption = "External Item Code";
externalItemCodeColumn.DisplayMember = "externalItemCodeColumn";
Sage.Common.Controls.GridColumn reasonColumn = new Sage.Common.Controls.GridColumn();
reasonColumn.Caption = "Reason";
reasonColumn.DisplayMember = "reasonColumn";
failedOrdersGrid.Columns.Add(externalItemCodeColumn);
failedOrdersGrid.Columns.Add(reasonColumn);
failedOrdersGrid.DataSource = FailedOrders;
//failedOrdersGrid.Refresh(); - this doesn't seem to make a difference
Please note that failedOrders is passed to another method hence the name change from failedOrders to FailedOrders.
Just to check that this behaviour is not specific to the Sage Grid, I tried populating a regular WinForms DGV with the DataTable. (Note - I disabled AutoGenerateColumns as this does not seem to be an option for the Sage Grid).
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Columns.Add("externalItemCodeColumn", "External Item Code");
dataGridView1.Columns.Add("reasonColumn", "Reason");
dataGridView1.DataSource = FailedOrders;
I expect the contents of the Sage Grid to match those of the DataGrid, but instead get blank rows.
The Sage.Common.Controls.Grid inherits from the Sage.Common.Controls.List and the DataSource property of Sage.Common.Controls.List requires on refresh that the new DataSource supports at least IList
(It literally just nulls out your datasource if it isn't an IList)
Here's an adaptation of your code to work with the Sage.Common.Controls.Grid
I added this to the constructor of my form (where failedOrdersGrid is of type Sage.Common.Controls.Grid):
List<Failure> failedOrders = new List<Failure>();
foreach (String item in new List<string> { "1", "2", "3" })
{
failedOrders.Add(new Failure { externalItemCodeColumn = item, reasonColumn = "Not enough available items in WAREHOUSE" });
}
Sage.Common.Controls.GridColumn externalItemCodeColumn = new Sage.Common.Controls.GridColumn();
externalItemCodeColumn.Caption = "External Item Code";
externalItemCodeColumn.DisplayMember = "externalItemCodeColumn";
Sage.Common.Controls.GridColumn reasonColumn = new Sage.Common.Controls.GridColumn();
reasonColumn.Caption = "Reason";
reasonColumn.DisplayMember = "reasonColumn";
failedOrdersGrid.Columns.Add(externalItemCodeColumn);
failedOrdersGrid.Columns.Add(reasonColumn);
failedOrdersGrid.DataSource = failedOrders;
And here's the failure class:
public class Failure
{
public string externalItemCodeColumn { get; set; }
public string reasonColumn { get; set; }
}
I'm working on a Windows Forms application, written with C#.
I found someone's suggestion on how to create a List<> from DataGridView control, but I need little more help on how to extract cell values.
Here is the code given; let's say two columns in the dataGridView1 are Name and Address.
How to build the List<ProjList> object?
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
ProjList = new List<ProjectMasterRec>();
foreach (DataGridViewCell dc in dr.Cells)
{
// build out MyItem
// based on DataGridViewCell.OwningColumn and DataGridViewCell.Value
// how do we code this?
}
ProjList.Add(item);
}
Try It this Way
Create a list of your class type
List<ProjectMasterRec>() ProjList = new List<ProjectMasterRec>();
Make Sure that type of list belongs to type of your data in Datagridview
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
//Create object of your list type pl
ProjectMasterRec pl = new ProjectMasterRec();
pl.Property1 = dr.Cells[1].Value;
pl.Property2 = dr.Cells[2].Value;
pl.Property3 = dr.Cells[3].Value;
//Add pl to your List
ProjList.Add(pl);
}
If you are able to use LINQ, you can do something like this:
var projectList = (from row in dataGridView1.Rows.OfType<DataGridViewRow>()
select new ProjectMasterRec()
{ Name = row.Cells["Name"].Value.ToString(),
Address = row.Cells["Address"].Value.ToString()
}).ToList();
The following should work, myArray should be an array of the type you need, you can find out the array size using (DataGrid1.DataSource as BindingSource).List.Count.
(DataGrid1.DataSource as BindingSource).List.CopyTo(myArray, 0);
In my DataGrid I used a ComboBox in the first column, so it will fetch some data from the database using the DisplayMember and ValueMember concepts. Now I want to remove the value from the ComboBox which is previously selected.
Populating the ComboBox code is given below:
dTable = getDummyTable.GetDummyTble("Dummy", "DNO", "All");
dCmbData = dTable;
cmbDeno.DataSource = dTable;
cmbDeno.DisplayMember = "dyName";
cmbDeno.ValueMember = "dyRemarks";
The next row of selection there should not be a duplicate value in the ComboBox.
How can I achieve this?
Can anyone help me with this?
well try this one out. You have the DataTable which you are using to bind all combos (correct me if I'm wrong). Now all we need to do is that when an item is selected from any combo, we need to remove that item from all the other combos). You will need to declare a class level dictionary to store which combo had what value stored previously:
IDictionary<ComboBox, DataRow> _prevSelection;
//Please don't mind if syntax is wrong worked too long in web
comboBox.OnSelectedIndexChanged += fixItems;
private void fixItems(object sender, EventArgs e)
{
var cbo= sender as ComboBox;
if(cbo==null) return;
var prev = _prevSelection[cbo];
var row=<GET ROW FROM DATATABLE FOR CURRENT SELECTED VALUE>;
_prevSelection[cbo] = row;
UpdateOtherCombos(cbo, prev, cbo.SelectedItem.Value);
}
private void UpdateOtherCombos(ComboBox cbo, DataRow prev, object toRemove)
{
foreach(var gridrow in <YourGrid>.Rows)
{
var c = <FIND COMBO IN ROW>;
if(cbo.Id == c.Id) continue;//combo that triggered this all
var itemToRemove=null;
foreach(var item in c.Items)
{
if(item.Value == toRemove)
{
itemToRemove = item;
break;
}
}
//or you can get index of item and remove using index
c.Items.Remove(itemToRemove);
//Now add the item that was previously selected in this combo (that
//triggered this all)
c.Items.Add(new ComboBoxItem{Value = prev["ValueColumn"],
Text = prev ["TextColumn"]});
}
}
This is just to give you an idea that may help you to find an optimal solution rather than iterating over all combos as it will slow down if you have too many rows in grid or too many items in combos. Still even with this you need to put up some functions/code to make it working. Also please note that I have not worked on WinForms for some time and you need to check if things like ComboBoxItem etc. and any functions called on them exist. :)
I've got a DataTable, dt2, where I'm trying to add new rows (in the else block of the code below). I cannot simply add the rows within the foreach loop (which I tried with the line dt2.Rows.Add(newRow);) because that screws up the loop counter or something and causes the following error: "Collection was modified; enumeration operation might not execute."
So I tried storing the new row values in a List and then adding the List to the table outside of the loop. This works in the sense that it compiles and it does add something; unfortunately it doesn't take the correct values or column locations but instead displays this crap: System.Collections.Generic.List`1[System.Object]
Also, the information should be displayed in the 3rd, 4th, and 5th index columns under Target_Folder, Target_File, and Target_Checksum, not under Baseline_Folder.
How do I store and display the correct values under the correct columns?
foreach (DataRow drow in dt2.Rows)
{
if (drow["BASELINE_FILE"].ToString() == filename)
{
// do stuff
}
else
{
newRow = dt2.NewRow(); // newRow is a DataRow I declared up above
newRow[3] = directory;
newRow[4] = filename;
newRow[5] = checksumList[j];
newRow[6] = "Missing";
//dt2.Rows.Add(newRow);
// can't add here because that increases the number of rows and screws up the foreach loop
// therefore need to find way to store these values and add outside of loop
newFiles.Add(newRow); // newFiles is a List
}
}
dt2.Rows.Add(newFiles); // this doesn't work properly, doesn't take correct values
I think this is what you really want to do :
DataRow[] drx = dt2.Select(string.Format("BASELINE_FILE = '{0}'" , filename));
if (drx.Length == 1)
{
// do stuff with drx[0]
}
else
{
newRow = dt2.NewRow(); // newRow is a DataRow I declared up above
newRow[3] = directory;
newRow[4] = filename;
newRow[5] = checksumList[j];
newRow[6] = "Missing";
dt2.Rows.Add(newRow);
}
This way you don't need to loop through the rows.
If you're looking to go through each row in the existing grid, this should do it for you. This way currentRows isn't being modified while loop is running as it will be a shallow copy of that list.
var currentRows = from row in dataTable.Rows select row;
foreach (var row in currentRows)
{
if(doStuffCondition){ doStuff();}
else{
DataRow newRow = dataTable.NewRow();
newRow[1] = newValue; //repeat until values are loaded
employeesDataTable.Rows.Add(newRow);
}
}
This is off the top of my head, but something along these lines should work:
DataRow dr = dt2.NewRow();
foreach (ListItem item in newFiles.Items)
{
dr[3] = item[3].ToString();
dr[4] = item[4].ToString();
etc.
}
If you need more guidance, let me know and I'll look harder at it.
I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me.
Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.
If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...
DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";
ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";
ddlOptions.DataBind();
Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.
A C# solution for .NET 3.5 (needs System.Linq and System.Web.UI):
public static void ReorderAlphabetized(this DropDownList ddl)
{
List<ListItem> listCopy = new List<ListItem>();
foreach (ListItem item in ddl.Items)
listCopy.Add(item);
ddl.Items.Clear();
foreach (ListItem item in listCopy.OrderBy(item => item.Text))
ddl.Items.Add(item);
}
Call it after you've bound your dropdownlist, e.g. OnPreRender:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ddlMyDropDown.ReorderAlphabetized();
}
Stick it in your utility library for easy re-use.
Assuming you are running the latest version of the .Net Framework this will work:
List<string> items = GetItemsFromSomewhere();
items.Sort((x, y) => string.Compare(x, y));
DropDownListId.DataSource = items;
DropDownListId.DataBind();
DropDownList takes any IEnumerable as a DataSource.
Just sort it using LINQ.
I usually load a DropDownList with values from a database table, so the easiest way is to sort your results as desired with the ORDER BY clause of your SELECT statement, and then just iterate through the results and dump them into the DropDownList.
Take a look at the this article from CodeProject, which rearranges the content of a dropdownlist. If you are databinding, you will need to run the sorter after the data is bound to the list.
It is recommended to sort the data before databinding it to the DropDownList but in case you can not, this is how you would sort the items in the DropDownList.
First you need a comparison class
Public Class ListItemComparer
Implements IComparer(Of ListItem)
Public Function Compare(ByVal x As ListItem, ByVal y As ListItem) As Integer _
Implements IComparer(Of ListItem).Compare
Dim c As New CaseInsensitiveComparer
Return c.Compare(x.Text, y.Text)
End Function
End Class
Then you need a method that will use this Comparer to sort the DropDownList
Public Shared Sub SortDropDown(ByVal cbo As DropDownList)
Dim lstListItems As New List(Of ListItem)
For Each li As ListItem In cbo.Items
lstListItems.Add(li)
Next
lstListItems.Sort(New ListItemComparer)
cbo.Items.Clear()
cbo.Items.AddRange(lstListItems.ToArray)
End Sub
Finally, call this function with your DropDownList (after it's been databound)
SortDropDown(cboMyDropDown)
P.S. Sorry but my choice of language is VB. You can use http://converter.telerik.com/ to convert the code from VB to C#
Another option is to put the ListItems into an array and sort.
int i = 0;
string[] array = new string[items.Count];
foreach (ListItem li in dropdownlist.items)
{
array[i] = li.ToString();
i++;
}
Array.Sort(array);
dropdownlist.DataSource = array;
dropdownlist.DataBind();
I agree with sorting using ORDER BY when populating with a database query, if all you want is to sort the displayed results alphabetically. Let the database engine do the work of sorting.
However, sometimes you want some other sort order besides alphabetical. For example, you might want a logical sequence like: New, Open, In Progress, Completed, Approved, Closed. In that case, you could add a column to the database table to explicitly set the sort order. Name it something like SortOrder or DisplaySortOrder. Then, in your SQL, you'd ORDER BY the sort order field (without retrieving that field).
What kind of object are you using for databinding? Typically I use Collection<T>, List<T>, or Queue<T> (depending on circumstances). These are relatively easy to sort using a custom delegate. See MSDN documentation on the Comparison(T) delegate.
var list = ddl.Items.Cast<ListItem>().OrderBy(x => x.Text).ToList();
ddl.DataSource = list;
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataBind();
Try it
-------Store Procedure-----(SQL)
USE [Your Database]
GO
CRATE PROC [dbo].[GetAllDataByID]
#ID int
AS
BEGIN
SELECT * FROM Your_Table
WHERE ID=#ID
ORDER BY Your_ColumnName
END
----------Default.aspx---------
<asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>
---------Default.aspx.cs-------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<YourTable> table= new List<YourTable>();
YourtableRepository tableRepo = new YourtableRepository();
int conuntryInfoID=1;
table= tableRepo.GetAllDataByID(ID);
ddlYourTable.DataSource = stateInfo;
ddlYourTable.DataTextField = "Your_ColumnName";
ddlYourTable.DataValueField = "ID";
ddlYourTable.DataBind();
}
}
-------LINQ Helper Class----
public class TableRepository
{
string connstr;
public TableRepository()
{
connstr = Settings.Default.YourTableConnectionString.ToString();
}
public List<YourTable> GetAllDataByID(int ID)
{
List<YourTable> table= new List<YourTable>();
using (YourTableDBDataContext dc = new YourTableDBDataContext ())
{
table= dc.GetAllDataByID(ID).ToList();
}
return table;
}
}
I agree with the folks in sorting your data in the model before populating them to the DropDownList, so if you are populating this from a DB, it is a good thing to get them sorted already there using a simple order by clause, it will save you some cycles in the web server, and I am sure the DB will do it so much faster.
If you are populating this from another data source for example, XML file, using LINQ will be a good idea, or even any variation of Array.Sort will be good.
If your data is coming to you as a System.Data.DataTable, call the DataTable's .Select() method, passing in "" for the filterExpression and "COLUMN1 ASC" (or whatever column you want to sort by) for the sort. This will return an array of DataRow objects, sorted as specified, that you can then iterate through and dump into the DropDownList.
List<ListItem> li = new List<ListItem>();
foreach (ListItem list in DropDownList1.Items)
{
li.Add(list);
}
li.Sort((x, y) => string.Compare(x.Text, y.Text));
DropDownList1.Items.Clear();
DropDownList1.DataSource = li;
DropDownList1.DataTextField = "Text";
DropDownList1.DataValueField = "Value";
DropDownList1.DataBind();
To sort an object datasource that returns a dataset you use the Sort property of the control.
Example usage In the aspx page to sort by ascending order of ColumnName
<asp:ObjectDataSource ID="dsData" runat="server" TableName="Data"
Sort="ColumnName ASC" />
is better if you sort the Source before Binding it to DropDwonList.
but sort DropDownList.Items like this:
Dim Lista_Items = New List(Of ListItem)
For Each item As ListItem In ddl.Items
Lista_Items.Add(item)
Next
Lista_Items.Sort(Function(x, y) String.Compare(x.Text, y.Text))
ddl.Items.Clear()
ddl.Items.AddRange(Lista_Items.ToArray())
(this case i sort by a string(the item's text), it could be the suplier's name, supplier's id)
the Sort() method is for every List(of ) / List<MyType>, you can use it.
You can do it this way is simple
private void SortDDL(ref DropDownList objDDL)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();
foreach (ListItem li in objDDL.Items)
{
textList.Add(li.Text);
}
textList.Sort();
foreach (object item in textList)
{
string value = objDDL.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
objDDL.Items.Clear();
for(int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
objDDL.Items.Add(objItem);
}
}
And call the method this SortDDL(ref yourDropDownList);
and that's it. The data in your dropdownlist will be sorted.
see http://www.codeproject.com/Articles/20131/Sorting-Dropdown-list-in-ASP-NET-using-C#
You can use this JavaScript function:
function sortlist(mylist)
{
var lb = document.getElementById(mylist);
arrTexts = new Array();
arrValues = new Array();
arrOldTexts = new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
arrValues[i] = lb.options[i].value;
arrOldTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++)
{
lb.options[i].text = arrTexts[i];
for(j=0; j<lb.length; j++)
{
if (arrTexts[i] == arrOldTexts[j])
{
lb.options[i].value = arrValues[j];
j = lb.length;
}
}
}
}
Try This:
/// <summary>
/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.
/// </summary>
/// <param name="dropDownList">The drop down list you wish to modify.</param>
/// <remarks></remarks>
private void AlphabetizeDropDownList(ref DropDownList dropDownList)
{
//Create a datatable to sort the drop down list items
DataTable machineDescriptionsTable = new DataTable();
machineDescriptionsTable.Columns.Add("DescriptionCode", typeof(string));
machineDescriptionsTable.Columns.Add("UnitIDString", typeof(string));
machineDescriptionsTable.AcceptChanges();
//Put each of the list items into the datatable
foreach (ListItem currentDropDownListItem in dropDownList.Items) {
string currentDropDownUnitIDString = currentDropDownListItem.Value;
string currentDropDownDescriptionCode = currentDropDownListItem.Text;
DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();
currentDropDownDataRow["DescriptionCode"] = currentDropDownDescriptionCode.Trim();
currentDropDownDataRow["UnitIDString"] = currentDropDownUnitIDString.Trim();
machineDescriptionsTable.Rows.Add(currentDropDownDataRow);
machineDescriptionsTable.AcceptChanges();
}
//Sort the data table by description
DataView sortedView = new DataView(machineDescriptionsTable);
sortedView.Sort = "DescriptionCode";
machineDescriptionsTable = sortedView.ToTable();
//Clear the items in the original dropdown list
dropDownList.Items.Clear();
//Create a dummy list item at the top
ListItem dummyListItem = new ListItem(" ", "-1");
dropDownList.Items.Add(dummyListItem);
//Begin transferring over the items alphabetically from the copy to the intended drop
downlist
foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {
string currentDropDownValue = currentDataRow["UnitIDString"].ToString().Trim();
string currentDropDownText = currentDataRow["DescriptionCode"].ToString().Trim();
ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);
//Don't deal with dummy values in the list we are transferring over
if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {
dropDownList.Items.Add(currentDropDownListItem);
}
}
}
This will take a given drop down list with a Text and a Value property of the list item and put them back into the given drop down list.
Best of Luck!
If you are adding options to the dropdown one by one without a dataset and you want to sort it later after adding items, here's a solution:
DataTable dtOptions = new DataTable();
DataColumn[] dcColumns = { new DataColumn("Text", Type.GetType("System.String")),
new DataColumn("Value", Type.GetType("System.String"))};
dtOptions.Columns.AddRange(dcColumns);
foreach (ListItem li in ddlOperation.Items)
{
DataRow dr = dtOptions.NewRow();
dr["Text"] = li.Text;
dr["Value"] = li.Value;
dtOptions.Rows.Add(dr);
}
DataView dv = dtOptions.DefaultView;
dv.Sort = "Text";
ddlOperation.Items.Clear();
ddlOperation.DataSource = dv;
ddlOperation.DataTextField = "Text";
ddlOperation.DataValueField = "Value";
ddlOperation.DataBind();
This would sort the dropdown items in alphabetical order.
If you are using a data bounded DropDownList, just go to the wizard and edit the bounding query by:
Goto the .aspx page (design view).
Click the magic Arrow ">"on the Dropdown List.
Select "Configure Data source".
Click Next.
On the right side of the opened window click "ORDER BY...".
You will have up two there field cariteria to sort by. Select the desired field and click OK, then click Finish.
You may not have access to the SQL, but if you have the DataSet or DataTable, you can certainly call the Sort() method.