How I Populate a list<> in two different Gridview - c#

Based on the answers and comments that I have been provide, I made the following modifications. Since I have other things than the two Gridviews I am not making any modifications to the load method. I am trying to split the collection when I bind it.
The Gridviews are:
<asp:GridView id ="gvClosed" runat = "server"/>
<asp:GridView id ="gvDraft" runat = "server"/>
The Bind:It does bind but the same data in both GV's
private void bindFiles(bool reload)
{
int size = 10;
List<File> closedFiles = new List<File>();
List<File> draftFiles = new List<File>();
if (ViewState["Files"] != null)
closedFiles = (List<File>)ViewState["Files"];
//draftFiles= (List<File>)ViewState["Drafts"];
else
closedFiles = loadFiles(((User)Session["currentUser"]).ID);
draftFiles = loadFiles(((User)Session["currentUser"]).ID);
List<File> listFiles = new List<File>();
foreach (File f in closedFiles)
listFiles.Add(f);
bool loadPrimary = Session["filterPrimary"] != null ? Convert.ToBoolean : false;
bool loadAll = Session["ViewAllUserFiles"] != null ? Convert.ToBoolean : false;
foreach (File d in draftFiles)
listFiles.Add(d);
if (loadPrimary)
listFiles = listFiles.FindAll(delegate(File f)
{
return f.Modified == true;
});
//Binding to the database
gvFiles.DataSource = listFiles;
gvFiles.DataBind();
gvDraftFiles.DataSource = listFiles;
gvDraftFiles.DataBind();
showHideSortArrows(gvFiles, GridViewType.File);
//showHideSortArrows(gvDraftFiles, GridViewType.Drafts);

Split your collection into two collections and then bind them separately individually to their appropriate GridViews. Better yet, pass a parameter to your loading method that you can use for your query to specify what sort of list you're trying to load. That way you can just load your lists using one method and not have to split anything.

If both lists contain the same data and you want to bind the same data to two or more controls, you can do that. you don't need to split it into different lists.
Even if you wish to bind only a subset of data to different controls, you can achieve that using Linq, since Linq resultsets are always IEnumerable of T.
For instance:
List<string> someList = GetStuffFromDatabase();
// binding to first control, all data
datagridControl1.DataSource = someList;
// binding to second control with subset of data
dropdownListControl1.DataSource = someList.AsEnumerable().Where( t => t.StartsWith("US-") );
and so on... The same applies to all kinds of collections... Dictionaries, et al.

ASPX:
<asp:GridView id="gvDraft" runat="server" />
<asp:GridView id="gvClosed" runat="server" />
C#:
closedList = new List<list>();
draftList = new List<list>();
if (ds.Tables.Count != 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
List ls = new List();
if (dr["list_id"] != DBNull.Value)
{
ls.ID = Convert.ToInt32(dr["list_id"]);
//I have more this is just for example
if(dr["WhateverIndicatesClosed"] == true)
{
closedList.Add(ls);
}else{
draftList.Add(ls);
}
}
}
}
gvDraft.DataSource = draftList;
gvDraft.DataBind();
gvClosed.DataSource = closedList;
gvClosed.DataBind();
You could also use linq to separate the lists, but as you are iterating through the dataset anyway, you may as well split the lists there.

Related

Setting checkbox selections in Grid View from comma separated list from SQL Server

I was wondering if anyone had an example of pulling a csv list of options from the database and checking the rows based on the text value pulled. So say I have a grid view with options showing various programming languages. I would like to match those languages to the ones that have been saved in the Database.
O ASP.NET
O C#
O VB.NET
...
So, if my returned list of languages is just ASP.NET and VB.NET, how do I get the checkboxes of those grid view rows to be checked? I could use View State but I am thinking more a data-based set of information by stepping through the recordset and checking the items based on the returned dataset.
Surprised I was able to figure this one out but suddenly the answer was staring me in the face.
protected void SetLangs()
{
List<string> sellangs = new List<string>();
string langs = hfPrgLangs.Value;
string langtrim = langs.Replace(" ", "");
sellangs = langtrim.Split(',').ToList<string>();
foreach (DataListItem dl in dlLanguages.Items)
{
Label lblLangName = (dl.FindControl("lblLangName") as Label);
CheckBox isChk = (dl.FindControl("cbLang") as CheckBox);
for (int i = 0; i < sellangs.Count; i++)
{
if (sellangs[i].ToString() == lblLangName.Text.ToString())
{
isChk.Checked = true;
}
}
}
}

how to display list<> in drop down list?

I have a dropdownlist where I want to display a list of users. To call the users I use ChatUserDetails.GetPXPUsers()
Which brings me to this code:
public static List<ChatUserDetails> GetPXPUsers()
{
List<ChatUserDetails> Users = new List<ChatUserDetails>();
string SQL = SelectPXPUsers;
DataTable dtMainItems = ChatUserDetails.CustomFill(SQL, null);
foreach (DataRow dr in dtMainItems.Rows)
{
Users.Add(new ChatUserDetails(dr));
}
return Users;
}
But how to I display this list of users in my dropdownlist?
<asp:DropDownList runat="server" ID="DropDownListPXPUsers"></asp:DropDownList>
You can bind your list to your drop down at runtime by using the following code. You will need to specify which properties of the object are to be used.
DropDownListPXPUsers.DataSource = GetPXPUsers();
DropDownListPXPUsers.DateTextField = "PropertyOne"; // name of 'ChatUserDetails' property
DropDownListPXPUsers.DataValueField = "PropertyTwo"; // name of 'ChatUserDetails' property
DropDownListPXPUsers.DataBind();
Read more: See Examples in the DropDownList documentation.
First you'll need to set the DataSource for the DropDownList and then you will need to call DataBind().
if(!IsPostBack)
{
DropDownListPXPUsers.DataSource = GetPXPUsers();
DropDownListPXPUsers.DataBind();
}

Get all <td> title of a table column with coded ui

I need to check a filter function on a table.
This filter is only on the first cell of each row and I'm trying to figure out how to get all those values...
I tried with something like
public bool CheckSearchResults(HtmlControl GridTable, string FilterTxt)
{
List<string> Elements = new List<string>();
foreach (HtmlCell cell in GridTable.GetChildren())
{
Elements.Add(cell.FilterProperties["title"]);
}
List<string> Results = Elements.FindAll(l => l.Contains(FilterTxt));
return Results.Count == Elements.Count;
}
but I get stuck at the foreach loop...
maybe there's a simply way with linq, but i don't know it so much
edit:
all the cells i need have the same custom html tag.
with this code i should get them all, but i don't know how to iterate
HtmlDocument Document = this.UIPageWindow.UIPageDocument;
HtmlControl GridTable = this.UIPageWindow.UIPageDocument.UIPageGridTable;
HtmlCell Cells = new HtmlCell(GridTable);
Cells.FilterProperties["custom_control"] = "firstCellOfRow";
also because there's no GetEnumerator function or query models for HtmlCell objects, which are part of Microsoft.VisualStudio.TestTools.UITesting.HtmlControl library -.-
edit2:
i found this article and i tried this
public bool CheckSearchResults(string FilterTxt)
{
HtmlDocument Document = this.UIPageWindow.UIPageDocument;
HtmlControl GridTable = this.UIPageWindow.UIPageDocument.UIPageGridTable;
HtmlRow rows = new HtmlRow(GridTable);
rows.SearchProperties[HtmlRow.PropertyNames.Class] = "ui-widget-content jqgrow ui-row-ltr";
HtmlControl cells = new HtmlControl(rows);
cells.SearchProperties["custom_control"] = "firstCellOfRow";
UITestControlCollection collection = cells.FindMatchingControls();
List<string> Elements = new List<string>();
foreach (UITestControl elem in collection)
{
HtmlCell cell = (HtmlCell)elem;
Elements.Add(cell.GetProperty("Title").ToString());
}
List<string> Results = Elements.FindAll(l => l.Contains(FilterTxt));
return Results.Count == Elements.Count;
}
but i get an empty collection...
Try Cell.Title or Cell.GetProperty("Title"). SearchProperties and FilterProperties are only there for searching for a UI element. They either come from the UIMap or from code if you fill them out with hand. Otherwise your code should should work.
Or you can use a LINQ query (?) like:
var FilteredElements =
from Cell in UIMap...GridTable.GetChildren()
where Cell.GetProperty("Title").ToString().Contains(FilterTxt)
select Cell;
You could also try to record a cell, add it to the UIMap, set its search or filter properties to match your filtering, then call UIMap...Cell.FindMatchingControls() and it should return all matching cells.
The problem now is that you are limiting your search for one row of the table. HtmlControl cells = new HtmlControl(rows); here the constructor parameter sets a search limit container and not the direct parent of the control. It should be the GridTable if you want to search all cells in the table. Best solution would be to use the recorder to get a cell control then modify its search and filter properties in the UIMap to match all cells you are looking for. Tho in my opinion you should stick with a hand coded filtering. Something like:
foreach(var row in GridTable.GetChildren())
{
foreach(var cell in row.GetChildren())
{
//filter cell here
}
}
Check with AccExplorer or the recorder if the hierarchy is right. You should also use debug to be sure if the loops are getting the right controls and see the properties of the cells so you will know if the filter function is right.
I resolved scraping pages html by myself
static public List<string> GetTdTitles(string htmlCode, string TdSearchPattern)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlCode);
HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//td[#" + TdSearchPattern + "]");
List<string> Results = new List<string>();
foreach (HtmlNode node in collection)
{
Results.Add(node.InnerText);
}
return Results;
}
I'm freakin' hating those stupid coded ui test -.-
btw, thanks for the help

Reversing default order of a drop down list

Is there an easy way to reverse the default order of a drop down list?
if (_group.Category == GroupCategory.Workers ||
_group.Category == GroupCategory.Acct)
{
this.cboList.DataSource = null;
this.cboList.DisplayMember = "DescForMCE";
this.cboList.ValueMember = "ID";
this.cboList.DataSource = _ch.Accounts;
this.cboList.Visible = true;
this.lblList.Visible = true;
}
You can reverse the order of the data source before you bind it.
if (_group.Category == GroupCategory.Workers ||
_group.Category == GroupCategory.Acct)
{
this.cboList.DataSource = null;
this.cboList.DisplayMember = "DescForMCE";
this.cboList.ValueMember = "ID";
this.cboList.DataSource = _ch.Accounts.Reverse();
this.cboList.Visible = true;
this.lblList.Visible = true;
}
Depending on the exact type and .NET version of your data source collection, it might not be quite as simple as the above example, which assumes that the data source implements IEnumerable<T> and can directly use the Reverse() extension method[MSDN].
If you only have an IEnumerable (the non-generic version) for instance, you can still accomplish in two calls using Cast<T>()[MSDN]:
collection.Cast<YourType>().Reverse();
Or your collection class might have its own implementation of Reverse(), like List<T>[MSDN] or Array[MSDN]
As other friends have suggested, it is better to fetch your data in a descending order and after that simply bind it to any control you may wish. Here is a stored procedure plus a LINQ query which bring data as you need:
The Linq query:
var queru = new DatabaseContext().Cities.OrderByDescending(s => s.CityID).ToList();
and the SP:
SELECT * FROM Roles
ORDER BY RoleID DESC
Hope it helps,
You can have the data you use for your datasource be in reverse before putting it in your dropdown list.
Use .Reverse.

Sorting a DropDownList? - C#, ASP.NET

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.

Categories