Bind Objects To DataGridview and Reorder Column - linq

I want to bind the object list to dataGridView.
Now i want the desired column to be the way i definde them. i.e., I want the objects to be order the way i want.
Like
var dataSource = linkItemListCommon.Select(x => new DataToBind { Select = x.Default, FileName = x.Text, CurrentDate = x.Date+" "+x.Time , PreviousDate = string.Empty, Size = x.Size }).ToList();
var filenamesList = new BindingList<DataToBind>(dataSource);
dgvDownLoadMaster.DataSource = filenamesList;
I want the datagrid columns to be in the order that i define.
Like here i expect them to be in order given below:
Select FileName CurrentDate PreviousDate Size
But the column list is appearing not as per my requirements.
How to Do that.Please help.

Create columns by hand and then you can order them easily. You can add columns trough designer and just set each column DataPropertyName to corresponding field.
Or you can create each column programmatically:
var col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Select ";
col.HeaderText = "Select";
col.Name = "ColSelect";
dgvDownLoadMaster.Columns.Add(col);
you have to do this for each column and do it before databinding.

Related

Oracle APEX - Interactive Grid - get the return value of the select list from each record

My Interactive Grid has column caled "EMPL_STAT1".
I use the code below to get the return value of the select list from selected record.
Works fine but I was wondering how to change that code to get the return value of the select list from each record (not selected only) in "EMPL_STAT1" column?
Could you give me any advice?
var reg = apex.region('ig_emp').widget();
var grid = reg.interactiveGrid("getViews","grid");
var model = reg.interactiveGrid("getViews","grid").model;
var selectedRecords = grid.getSelectedRecords();
for (i = 0; i < selectedRecords.length; i++)
{
record = model.getRecord(selectedRecords[i][0]);
itemcodeField = model.getFieldKey("EMPL_STAT1");
alert(record[itemcodeField].v);
}
The Javascript you shared, gets the selected row records only.
Let's say my IG's static ID is igTest
var model = apex.region("igTest").widget().interactiveGrid("getViews", "grid").model;
model.forEach(function(igrow) {
console.log(igrow[model.getFieldKey("FIRST_NAME")]);
});
This will loop through all the records in the IG.

Insert formatted values as currency type while using EPPlus

I am using format:
type ="$###,###,##0.00"
for currency and assigning the format type to the worksheet cells
eg.
wrkSheet.Cells[0].Style.Numberformat.Format = formatType;
But this is inserted as text type in excel.
I want this to be inserted as Currency or Number in order to continue to do analysis on the values inserted (sort, sum etc).
Currently as it is text type validations do not hold correct.
Is there any way to force the type in which the formatted values can be inserted?
Your formatting is correct. You needs to covert values to its native types
Use this code, it should work:
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Sales list - ");
worksheet.Cells[1, 1].Style.Numberformat.Format = "$###,###,##0.00";
worksheet.Cells[1, 1].Value =Convert.ToDecimal(24558.4780);
package.SaveAs(new FileInfo(path));
}
Indices start from 1 in Excel.
This code
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Sales list - ");
worksheet.Cells[1, 1].Style.Numberformat.Format = "$###,###,##0.00";
worksheet.Cells[1, 1].Value = 24558.4780;
package.SaveAs(new FileInfo(path));
}
produces $24 558,48 for me

Get IGrouping data in Repeater ItemDataBound

I am wanting to group news articles by year in a repeater. The format would be:
2010
list of articles
2011
List of Articles
My access layer returns a flat list of news articles, specifically List. Therefore, I am grouping them and binding them to the Repeater as follows:
events = DAL.GetEvents();
var groupedNewsList = from e in events
group e by e.StoryDate.Year
into g
select new {
Year = g.Key
, Events = g
};
rptEvents.DataSource = groupedNewsList;
rptEvents.DataBind();
The problem is trying to get the List from within the ItemDataBound event. So far, I have the following:
var data = e.Item.DataItem;
System.Type type = data.GetType();
// getting the year works fine
string year = (string)type.GetProperty("Year").GetValue(data, null).ToString();
// this returns something, but I can't access any properties. I need to get
//access to the contained List<News>
var newsList = type.GetProperty("Events").GetValue(data, null);
Any ideas?
Thanks in advance!
You don't have a List<News> - you just have a grouping. If you want a List<News>, you'll need to change your query, e.g.
var groupedNewsList = from e in events
group e by e.StoryDate.Year into g
select new { Year = g.Key, Events = g.ToList() };
Note that if you're using C# 4 you could do reflection rather more easily using dynamic typing:
dynamic data = e.Item.DataItem;
string year = data.Year.ToString();
List<News> newsList = data.Events;
Alternatively, you could avoid using an anonymous type in the first place - create your own GroupedNewsList type with Year and Events properties, populate that in your query, and then cast to it in your event handler.
The "sender" object in the ItemDataBound event is the repeater -- use it to get to the data-source. If the data-source has been grouped before binding, you can compare the current value to the previous value & hide the year-field if they are equal. Like this:
MyObject item = (MyObject)item.DataItem;
Repeater repeater = (sender as Repeater);
List<MyObject> items = repeater.DataSource as List<MyObject>;
Label lblGrouping = (Label)item.FindControl("lblGrouping");
if (item.ItemIndex == 0 || item.DateField.Year != items[item.ItemIndex - 1].DateField.Year) {
lblGrouping.Text = item.DateField.Year.ToString();
}
This worked for me, as I used a table with each row being one item, and the left-most column contained the "lblGrouping" control.

Conversion directly in LINQ query

I work with the Entity Framework and I have a LINQ query like this:
var foo = from ee in context.Table select new {id = ee.id, price = ee.price}.ToList();
where price is decimal (smallmoney in SqlServer).
Now I bind it to a datagridview by
mydgv.DataSource = foo;
But first, I would like to convert all the decimals to strings in order to remove zeros from the value (ex. now it is 26.0000 and I want it to be 26.00). How can I do that?
Something like:
bla.ForEach( x => x.price.ToString().Substring(0,3))
won't work.
var q = foo.Select(x => new { id = x.id, price = x.price.ToString("N2") } );
But you can probably set a format-string on the column in the datagridview to "N2" and bind directly to your original datasource. Something like:
dgv.Columns[0].DefaultCellStyle.Format = "N2";
Not sure if EF supports it, but try
new { ee.id, price = ee.price.ToString("f2") }

Update entity columns iterating through col list using LINQ

I can get column list from the table using LINQ like this:
OrderDataContext ctx = new OrderDataContext();
var cols = ctx.Mapping.MappingSource
.GetModel( typeof( OrderDataContext ) )
.GetMetaType( typeof( ProductInformation ) )
.DataMembers;
This gives me the list of columns, so I can do this:
foreach ( var col in cols )
{
// Get the value of this column from another table
GetPositionForThisField( col.Name );
}
So this all works, I can iterate through column list and pull the values for those columns from an another table (since the column names are the keys in that another table), so I don't have to do switch....or lot of if...then...
Now the question:
After I get these values, how do I populate the entity in order to save it back? I would normally go like this:
ProductInformation info = new ProductInformation();
info.SomeField1 = val1;
info.SomeField2 = val2;
ctx.ProductInformation.InsertOnSubmit( info );
ctx.SubmitChanges();
But how to use the same column collection from above to populate the columns while iterating over that, when there is no such thing as:
info["field1"].Value = val1;
Thanks.
Just fetch the object that you want to modofy, set the property and call SubmitChanges. There is no need to create a new object and insert it. The Context tracks your changed properties and generates the update statement accordingly. In your case you may want to set the properties via reflection rather than manually since you are reading them from another table.
You'll need to use reflection. Assuming you can get the PropertyInfo from the metadata:
PropertyInfo property = GetPropertyForThisField(col.Name);
property.SetValue(info, val1, null);

Resources