I have a small DataTable that contains a number of rows which I am running a LINQ query against.
I am having problems getting the LINQ to display the text that is in the datatable.
When I run it I can get the column name.
I have tried a number of different ways of doing it but to no avail.
Code as follows:
DataTable DTGetNarratives = DAL.GetNarrativeList();
var SelectedNarrative =
from n in DTGetNarratives.AsEnumerable()
where n.Field<string>("narr_code").Equals(ClsPublic.NarrativeCode)
select n;
foreach (var item in SelectedNarrative)
{
//test1.Add(item.Table.Columns[col].ToString());
//col++;
txtLine1.Text = item.Table.Columns[0].DefaultValue.ToString();
}
Any help on this would be great.
So you have one TextBox but an IEnumerable<DataRow>. Do you expect a single row? If not, how do you want to diplays multiple records on a single textbox?
You could comma separate them:
var allNarrCode = SelectedNarrative.Select(r => r.Field<string>("narr_code"));
txtLine1.text = string.Join(",", allNarrCode);
or as multiline TextBox use the Lines property:
txtLine1.Lines = allNarrCode.ToArray();
Only the first:
txtLine1.Text = SelectedNarrative.FirstOrDefault();
without LINQ:
foreach (DataRow row in SelectedNarrative)
{
string code = row.Field<string>("narr_code")
// the next line is pointless since you're overwriting the text on every row
//txtLine1.Text = code;
}
You can use the Field extension method like:
foreach (var item in SelectedNarrative)
{
txtLine1.Text = item.Field<string>("narr_code"); //here
}
(You can specify the column name in the method parameters)
I am not sure if you really need that since your TextBox would be populated with the last row's value.
To show all values in a single TextBox you can do:
txtLine1.Text = string.Join(" ",SelectedNarrative.Select(r=> r.Field<string>("narr_code")));
Or you can do
StringBuilder sb = new StringBuilder();
foreach (var item in SelectedNarrative)
{
sb.Append(item.Field<string>("narr_code"));
}
txtLine1.Text = sb.ToString();
Related
I have two list. First list has matched column which is available in second list.
I want to show matched columns with values from second list.
List<string> _filtredData = new List<string>();
_filtredData.Add("Broker");
_filtredData.Add("Loaction");
_filtredData.Add("StandardLineItem");
_filtredData.Add("Section");
foreach (DataColumn _dtCol in FinalDiffData.Columns)
{
if (matchedItems.Contains(_dtCol.ToString()))
{
_filtredData.Add(_dtCol.ToString());
}
}
_filtredData -> contains matched columns which available in Second list.
FinalDiffData.AsEnumerable() -> this is secondlist.
List<string> _filtredData = new List<string>();
_filtredData.Add("Broker");
_filtredData.Add("Loaction");
_filtredData.Add("StandardLineItem");
_filtredData.Add("Section");
foreach (DataColumn _dtCol in FinalDiffData.Columns)
{
if (matchedItems.Contains(_dtCol.ToString()))
{
_filtredData.Add(_dtCol.ToString());
}
}
var shortedListMismatchElementLocal = _filtredData;
var result = FinalDiffData.AsEnumerable().Where(p =>
shortedListMismatchElementLocal.Any());
Please help me with proper answer.
Edit from your last comment
FinalDiffData.AsEnumerable() list has column like
Broker, Loaction, StandardLineItem, Section, 2Q2019E, 3Q2019E, 4Q2019E, 2019E, 1Q2020E
etc as earning order. _filtredData list has
Broker, Loaction, StandardLineItem, Section, 2Q2019E, 3Q2019E, 4Q2019E,
I want to get matched column with value from FinalDiffData.AsEnumerable() which available in _filtredData list
You need to compare a List<string> with a DataTable. You're only interested in one column in the datatable (I'll assume the column name is "Data").
The following query will get all rows in column "Data" matching _filteredData.
var result = FinalDiffData
.AsEnumerable()
.Where(p => _filtredData.Contains(p["Data"])); // use the actual column name here
Is there any way to remove "columns" from an ArrayList?
I got this site up and running before attempting populating my DropDownLists from txt files so I hard-typed each value in. Now I've made an ArrayList from each DropDownList so I can display those lists in DataGridView on the site. The only issue is that "Enabled" and "Selected" show up as columns and I cannot seem to remove the column in the ArrayList, or specify which columns to bring in when creating the ArrayList, or GridView using GridView.Columns.Remove(); because the integers 0 or 1 or 2 don't seem to correspond with anything and the site doesn't run and I can't specify a string as the column title for what to remove.
The DataGrids show up with columns as |Enabled|Selected|Text|Value|
Here's the code for this piece as it stands (You can see what I've tried out and that didn't work that I've commented away):
// Create ListArrays from DropDownLists
ArrayList BuildingList = new ArrayList(Building.Items);
ArrayList DepartmentList = new ArrayList(Department.Items);
//Building.Items.Remove("Enabled");
//Building.Items.Remove("Selected");
// Populate Building GridView
BuildingGrid.DataSource = BuildingList;
BuildingGrid.DataBind();
//BuildingGrid.Columns.Remove;
//BuildingGrid.Columns[0].Visible = false;
// Populate Department GridView
DepartmentGrid.DataSource = DepartmentList;
DepartmentGrid.DataBind();
//DepartmentGrid.Columns[0].Visible = false;
//DepartmentGrid.Columns[1].Visible = false;
I would just go ahead and create a simple 2d array in a txt file with fields for "Value" and "Text" so the DropDownList will pull it in properly, but I can't figure that out either without being terribly inefficient and confusing.
Any help would be appreciated. Thanks.
So, here's the solution I ended up at. I finally figured out how to extract everything from a txt file, and place it into the grid the way I wanted to.
// Populate Department GridView
// get all lines of csv file
string[] BuildingString = File.ReadAllLines(Server.MapPath("Content/BuildingsCSV.csv"));
string[] DepartmentString = File.ReadAllLines(Server.MapPath("Content/DepartmentsCSV.csv"));
// create new datatable
DataTable BuildingTable = new DataTable();
DataTable DepartmentTable = new DataTable();
// Building Table
// get the column header means first line
string[] tempbuild = BuildingString[0].Split(',');
// creates columns of gridview as per the header name
foreach (string t in tempbuild)
{
BuildingTable.Columns.Add(t, typeof(string));
}
// now retrive the record from second line and add it to datatable
for (int i = 1; i < BuildingString.Length; i++)
{
string[] t = BuildingString[i].Split(',');
BuildingTable.Rows.Add(t);
}
// Department Table
// get the column header means first line
string[] tempdept = DepartmentString[0].Split(',');
// creates columns of gridview as per the header name
foreach (string t in tempdept)
{
DepartmentTable.Columns.Add(t, typeof(string));
}
// now retrive the record from second line and add it to datatable
for (int i = 1; i < DepartmentString.Length; i++)
{
string[] t = DepartmentString[i].Split(',');
DepartmentTable.Rows.Add(t);
}
// assign gridview datasource property by datatable
BuildingGrid.DataSource = BuildingTable;
BuildingGrid.DataBind();
BuildingGrid.Rows[0].Visible = false;
DepartmentGrid.DataSource = DepartmentTable;
DepartmentGrid.DataBind();
DepartmentGrid.Rows[0].Visible = false;
foreach (DataRow drb in BuildingTable.Rows)
{
BuildingDrop.Items.Add(new ListItem(drb[0].ToString(), drb[1].ToString()));
}
foreach (DataRow drd in DepartmentTable.Rows)
{
DepartmentDrop.Items.Add(new ListItem(drd[0].ToString(), drd[1].ToString()));
}
I found this code to take values from CheckedListBox with commas. But there is no Selected and Value definition for CheckedListBox object. (there are just 4 basic inheritances :Equals(), GetHashCode(), GetType(), ToString())
Which reference I need or how can I correct this error?
I put that image to show where it throws me error, here is the code:
string values = "";
for (int i = 0; i < clSiparisTipi.Items.Count; i++)
{
if (clSiparisTipi.Items[i].Selected)
{
values += clSiparisTipi.Items[i].Value + ",";
}
}
values = values.TrimEnd(',');
Edit: I also tried this code:
StringBuilder items = new StringBuilder();
foreach (var item in checkedListBox1.CheckedItems)
{
items.Append(item).Append(",");
}
MessageBox.Show(items.ToString().TrimEnd(','));
But for example when I chose two items from the list, giving me such result: System.Data.DataRowView,System.Data.DataRowView
CheckedListBox exposes a SelectedItems collection.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems(v=vs.110).aspx
This in turn exposes a count and it's Item's are accessible via an index.
StringBuilder sb = new StringBuilder();
foreach(var item in clSiparisTipi.SelectedItems){
sb.Append((String)item.Value)
.Append(",");
}
// Remove trailing comma
sb.Remove(sb.Length-1,1);
string values = sb.ToString();
That should do the trick. Also be aware that concatenating strings is somewhat expensive. It's faster to use a StringBuilder whenever possible.
I solved my problem with this code (I guess I would mention about how do I populate items in my question)
StringBuilder items = new StringBuilder();
foreach (object checkedItem in clSiparisTipi.CheckedItems)
{
DataRowView dr = (DataRowView)checkedItem;
items.Append(dr["tanimId"]).Append(",");
}
MessageBox.Show(items.ToString().TrimEnd(','));
Once I done in this way..
var items = new StringBuilder();
foreach (Object ss in checkedListBox1.CheckedItems)
items.Append(string.Format("{0},",ss.ToString()));
Struggeling with some LinqToExcel filtering here...
Ive got a List<string> columnsToFilter that contains 9 strings, and with that i want to filter out the data for certain columns in a List<Row>, where Row contains the properties
IEnumerable<string> ColumnNames
Cell this[string columnName]
So: List<Row> has say 30 rows, each having 12 ColumnNames. Now i want to filter that List<Row> using List<string> columnsToFilter so that i end up with a List<Row> of 30 rows and 9 ColumnNames.
I can select the data for one column by quering the columnname:
var result = content.Select(m => m["Column1"]).ToList();
Now i want to filter the data based on a List of strings List<string> columnsToFilter. Whats the best way to achieve that?
Is this what you are looking for?
var colnames = new List<string>();
var rows = new Dictionary<string, object>();
var result = rows.Where(kv => colnames.Contains(kv.Key)).Select(kv => kv.Value);
Define an object called MyObject which has the property names corresponding to the 9 columns that you want to select.
var excel = new ExcelQueryFactory("excelFileName");
var myObjects = from c in excel.Worksheet<MyObject>()
select c;
Bingo. You can now iterate through the 30 objects with the 9 columns as properties.
Remember that LinqToExcel will happily fill objects even if they don't have all the columns represented.
You could even have a property or method as part of MyObject called "row" that would be a Dictionary() object so you could say myObject.row["ColumnName"] to reference a value if you preferred that syntax to just saying myObject.ColumnName to get the value. Personally I would rather deal with actual properties than to use the dictionary convolution.
I ended up doing this in two steps:
foreach (var column in columnNumbers)
{
yield return data.Select(m => m[column].Value.ToString()).ToList();
}
Now I have the data I need, but with the rows and columns swapped, so i had to swap rows for columns and vice versa:
for (int i = 1; i < rowCount; i++)
{
var newRow = new List<string>();
foreach (var cell in list)
{
newRow.Add(cell[i]);
}
yield return newRow;
}
I have a dataset called "results" with several rows of data. I'd like to get this data into a string, but I can't quite figure out how to do it. I'm using the below code:
string output = "";
foreach (DataRow rows in results.Tables[0].Rows)
{
output = output + rows.ToString() + "\n";
}
However, I think I'm missing something because this isn't working. Can someone point me in the right direction?
You need to specify which column of the datarow you want to pull data from.
Try the following:
StringBuilder output = new StringBuilder();
foreach (DataRow rows in results.Tables[0].Rows)
{
foreach (DataColumn col in results.Tables[0].Columns)
{
output.AppendFormat("{0} ", rows[col]);
}
output.AppendLine();
}
I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:
StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)
{
sb.AppendLine(string.Join(",", row.ItemArray));
}
A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.
You can get a columns value by doing this
rows["ColumnName"]
You will also have to cast to the appropriate type.
output += (string)rows["ColumnName"]
Your rows object holds an Item attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString() on the row.
You should access each column from the row separately, use a for or a foreach to walk the array of columns.
Here, take a look at the class:
http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx