Get the column name from list - c#

I would like to fetch the column names from List. As I have a class
public class DetailView
{
public string SiteName { get; set; }
public string ItemType { get; set; }
public string AssetStorage { get; set; }
}
and in some method in controller am filling the data into Session. Now I want to get the column names for some reason. Am putting my session data into that list.
List<DetailView> objgrdDtls = new List<DetailView>();
objgrdDtls = (List<DetailView>)Session["datasetVal"];
I would like to have the Column name. Pleas note by doing the below code i got the value of that particular column name. restult1 has the column value.
var result1 = objgrdDtls.Where(p => p.SiteName.ToLower().Contains(txt1));
But all i need is Column name. So how do i get that.
stringColumnname = objgrdDtls.get(columnaname => some filter)?
Is this is the way how to get column names?
Not sure how to get the column name one by one?
Thanks.

You can use reflection to get the column name. Here is the runnable example to get the column name of DetailView.
using System;
using System.Reflection;
public class DetailView
{
public string SiteName { get; set; }
public string ItemType { get; set; }
public string AssetStorage { get; set; }
}
public class Example
{
public static void Main()
{
DetailView fieldsInst = new DetailView();
// Get the type of DetailView.
Type fieldsType = typeof(DetailView);
PropertyInfo[] props = fieldsType.GetProperties(BindingFlags.Public
| BindingFlags.Instance);
for(int i = 0; i < props.Length; i++)
{
Console.WriteLine(" {0}",
props[i].Name);
}
}
}

Var result1 will give the list of DetailView Objects which meet the condition "SiteName.ToLower().Contains(txt1)". It will not be a value. Can you please clarify what do you mean by column value. However, For selecting a particular column value, You can append ".Select(p => p.AssetStorage)".

Related

Dictionary Creation from a multi layer class

I have the following model:
public class IP_BankInfo
{
public App.BankType BankType { get; set; }
public string FileExtension { get; set; }
public List<IP_BankRows> Rows { get; set; }
}
public class IP_BankRows
{
public int RowIndex { get; set; }
public List<IP_BankBindings> Bindings { get; set; }
}
public class IP_BankBindings
{
public int ColumnIndex { get; set; }
public string ExpectedHeader { get; set; }
public string TransactionPropertyName { get; set; }
}
Where for the post-processing, I am interested in IP_BankBindings - ColumnIndex and TransactionPropertyName. What I would like to do, is to create a new Dictionary<int,string> which will hold the above metioned.
I have tried to retrieve them via LINQ:
var items = info.Rows.Where(n => n.Bindings.Where(x => x.TransactionPropertyName.Length > 0));
However with no luck. Any suggestion would be welcome (maybe Dictionary is not the right type).
P.S. what I do afterwards is, that I have a CSV file which I read row by row, and these give me column index position and the target property I am interested in.
You can get the BankBindings using SelectMany()
var query = info.Rows
.SelectMany(r => r.Bindings)
.Where(x => x.TransactionPropertyName != null && x.TransactionPropertyName.Length > 0);
what I do afterwards is, that I have a CSV file which I read row by row, and these give me column index position and the target property I am interested in.
Do you mean TransactionPropertyName? To further get the ColumnIndex and TransactionPropertyName
var dataForCsv = query
.Select(b => new { b.ColumnIndex, b.TransactionPropertyName});
You can then loop through dataForCsv, writing the two properties to your CSV file.

DataValue field value C#

I am doing a project and can't make a Seletect Value from a list get the right value.A list is generated from a class UserDepartment,in this class I have this basically:
public class UserDepartment
{
public long ID { get; set; }
public string Description { get; set; }
public User UserResponsible { get; set; }
}
The Problem is that I need a value from the class userResponsible,inside there is a value called EDV, I need this value but I don't know how to get.See this image below:
If I use " ListBeneficiaryArea.DataValueField = "ID"; ",I get the ID value normally,but i cant get the EDV value, I already tried "EDV","UserResponsible.EDV" and "UserResponsible"but it didn't work.
There is other way for me to get the UserResponsible.EDV in the DataValueField?
After the change in DataSource i received this error:
You can change your DataSource to the following:
ListBeneficiaryArea.DataSource = from a in lstBUAreas
select new { ID, EDV = a.UserResponsible.EDV };
Then you can do:
ListBeneficiaryArea.DataTextField = "ID";
ListBeneficiaryArea.DataValueField = "EDV";

Creating custom linq column names in list

We are returning a generic List to a GridView, which then auto generates columns to show a report:
//Generate List
List<Stock> allStock = blStock_Collection.getAll();
//export custom view for report datagrid
return (from myStock in allStock
select new
{
myStock.Category,
myStock.Description,
myLowStock.UnitPrice,
myLowStock.CurrentQuantity
});
Our client has asked that we now provide multi-lingual support on our site (English & Polish), specifically the column headers on grids. We would therefore need to get rid of the auto generate option on all our data grids, and add in the translations manually for each column.
I was wondering is there a way to do this when generating the datasource, which would save us a hell of a lot of time, e.g. changing this line:
myStock.Category,
to something like:
languagePack.Category = myStock.Category,
This is of course throwing a 'Invalid anonymous type member declarator' error. Any advice?
Maybe I misread something, but if you just want to put your language into it (LanguagePack is just a class holding your values):
class LanguagePack
{
public int Category { get; set; }
public string Description { get; set; }
public decimal UnitPrice { get; set; }
public int CurrentQuantity { get; set; }
public int LanguageName { get; set; }
}
return (from myStock in allStock
select new LanguagePack
{
Category = myStock.Category,
Description = myStock.Description,
UnitPrice = myLowStock.UnitPrice,
CurrentQuantity = myLowStock.CurrentQuantity,
LanguageName = "Polish" // or english or whatever... maybe LanguageId or something corresponding to your model
});

Properties and objects C#

I want to make public property that gets and sets object I get from datagrid.
I have datagrid that has 3 columns with text and 3 columns with checkboxes.
When I check one of the checkbox I get a value of whole row in list like this:
var selectedItemsController = MyObsCollection.Where(n => n.Controller).ToList();
That is a list of objects with all 3 string values (and all 3 bool values of checkboxes) that are in same row where checkboxes in column named Controller is.
MyObsCollection is also public property for ObservableCollection and they are defined like this:
ObservableCollection<RowData> _obsCollection =
new ObservableCollection<RowData>();
public ObservableCollection<RowData> MyObsCollection
{
get { return _obsCollection; }
}
RowData is my class that caries a model I need and it's defined like this:
public class RowData : INotifyPropertyChanged
{
public string Type { get; set; }
public string MapTo { get; set; }
public string Name { get; set; }
public bool Controller { get; set; }
public bool Service { get; set; }
public bool Injection { get; set; }
public RowData(string type, string mapTo, string name)
{
Type = type;
MapTo = mapTo;
Name = name;
}
What I'm trying to do is to make a public property for that list of objects(in selectedItemsController) so I can use it in other class.
For example I was doing this with name for some Area that is also part of WindowsForm. I was taking the name from some text box and making public property like this:
public string AreaName
{
get { return AreaNameValue.Text; }
set { AreaNameValue.Text = value; }
}
And after that I was able to do this in other class:
var areaName = areaDialog.AreaName.Trim();
So finally my question is does someone know how can I make same public property for DataRow object if the name of DataGrid is for example: tabela? Is there something already defined in DataGrid that I can use? (like 'Text' property is for InputTextBoxes).
You can set your selectedItemsController as the datacontext of your DataGrid. Then you can set and get values on the selectedItemsController itself.

Unable to cast anonymous object to System.Data.DataRowView

I use to linq to sql to fill a gridview:
var results = from r in db.MyForm1_hosps
where r.recordId == recordId
orderby r.hospId
select new { r.hospId, r.which, r.description };
if (results.Count() > 0)
{
Form_1_hosp.DataSource = results;
Form_1_hosp.DataBind();
}
later during OnRowDataBound, i call the following code to fill in the value of a radiobuttonlist
if (e.Row.RowType == DataControlRowType.DataRow)
{
RadioButtonList rbl = e.Row.FindControl("which") as RadioButtonList;
if (rbl != null)
{
DataRowView rowView = (DataRowView)(e.Row.DataItem);
LoadRadioButtonList(rowView["which"], rbl);
}
}
I get the following error:
Unable to cast object of type '<>f__AnonymousType1`3[System.Int32,System.Int16,System.String]' to type 'System.Data.DataRowView'.
I understand that an anonymous object cannot be cast to a datarowview, but what can I cast to in order to get the value of "which"
You should define a proper class to describe your data, and then you will be able to cast to this class.
// replace with proper names and types, as appropriate
class MyData
{
public int HospId { get; set; }
public string Which { get; set; }
public string Description { get; set; }
}
Update your query's select to utilize this class for the projection
select new MyData
{
HospId = r.hospId,
Which = r.which,
Description = r.description
};
And then use the type for the cast.
MyData obj = (MyData)(e.Row.DataItem);
LoadRadioButtonList(obj.Which, rbl);
There are other techniques for dealing with this, such as using dynamic and letting the runtime figure it out, or using a CastByExample<T> method (you can look it up, but I consider it faily hack-ish), but this is in my opinion the cleanest thing to do.
You could arguably also simply omit the projection and use the full object
select r;
At which point you would simply cast to the type of the elements in db.MyForm1_hosps, which is presumably MyForm1_hosp (you would have to verify). The counter against this approach would be if your UI container is auto-generating columns and this class contains more data than you wish to display, in which case, you would want to continue with the projection into a smaller construct.
Anthony's answer worked perfectly for me as well, though I'm doing things slightly differently. My goal is to display information related to tax filings and electronic funds transfers.
I'm using a RadioButtonList in an ItemTemplate. Each added item has it's own value ("Y" or "N") which corresponds to the string stored in the database.
<asp:TemplateField HeaderStyle-CssClass="TableHeader" HeaderText="Pay Estimate by EFT?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:RadioButtonList ID="rdoPayEstbyEFT" runat="server">
<asp:ListItem Value="Y">Yes</asp:ListItem>
<asp:ListItem Value="N">No</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
I created a class called EFT to define all the data I'm retrieving in my LINQ to SQL statement
public class EFT
{
public int JUR_ID {get; set;}
public string JUR_NAME {get; set;}
public DateTime FYE {get; set;}
public int STATE {get; set;}
public string ENT_NAME { get; set; }
public string ENT_ABBREV { get; set; }
public string TYPE_NAME { get; set; }
public int RETURN_ID { get; set; }
public string EFT_EST { get; set; }
public string EFT_EXT { get; set; }
public string EFT_RETURN { get; set; }
}
then modified the LINQ to SQL to select a new instance of that class (jurisdictions, entity, taxtypes, and returns all reference joins that are not displayed here).
select new EFT {JUR_ID = jurisdictions.ID, JUR_NAME = jurisdictions.NAME, FYE = jurisdictions.FYE.Value , STATE = jurisdictions.STATE.Value , ENT_NAME = (entity.NAME.Contains(",") ? entity.NAME.Substring(0, entity.NAME.IndexOf(",") -1).ToString() : entity.NAME ), ENT_ABBREV = entity.ABBREV, TYPE_NAME = taxtypes.TYPE, RETURN_ID = returns.RETURN_ID.Value, EFT_EST = returns.EFT_EST, EFT_EXT = returns.EFT_EXT, EFT_RETURN = returns.EFT_RETURN }
).ToList();
Then in my RowDataBound I'm extracting the "Y" or "N" value from the database and assigning that string to the selected value.
RadioButtonList rdoPayEstbyEFT = (RadioButtonList)e.Row.FindControl("rdoPayEstbyEFT");
EFT rowView = (EFT)e.Row.DataItem;
string strESTbyEFT = rowView.EFT_EST.ToString();
rdoPayEstbyEFT.SelectedValue = strESTbyEFT;
Works like a charm!

Categories