Large object on ViewState - c#

I am storing object of a class on a ViewState. It has 3 string variables. But when ever one string gets larger (more than 400 chars) Pagination stops working.
I have tried so many things but no luck.
So I need to think of another Session Management method?
public class Productx
{
public bool check { get; set; } // ForMultiProduct Page - Selected or not
public string imagePathSmall { get; set; }
public string imagePathLarge { get; set; }
public int Id { get; set; }
public int RatingCount { get; set; }
public string SetName { get; set; }
public string Description { get; set; }
public string KeyWords { get; set; }
public int FavourCount { get; set; }
}
public List<Productx> ArticleList
{
get
{
if (this.ViewState["ArticleList"] != null)
{
return (List<Productx>)(this.ViewState["ArticleList"]);
}
return new List<Productx>();
}
set { this.ViewState["ArticleList"] = value; }
}
List<Productx> al = new List<Productx>();
foreach (DataRow dr in tblProducts.Rows)
{
Productx a = new Productx();
a.check = false;
a.Id = Convert.ToInt32(dr["ID"].ToString());
a.RatingCount = Convert.ToInt32(dr["RATING_COUNT_BY_CAT"].ToString());
string s = dr["KEY_WORDS"].ToString();
a.KeyWords = s;
a.FavourCount = Convert.ToInt32(dr["FAVORITE_COUNT"].ToString());
al.Add(a);
}
if (al.Count > 0) ArticleList = al;

Related

using jsonData as a key value to send mixed data in asp: Does not update the database with the values

After trying to mix a fileupload and json data in postman i finally found a method where it is possible to send them both in the same request. Therefore, I have moved my json data to a Key in Postman, so that it becomes possible to send files as well using form-data (Picture below).
Within the value I have JSON data as following:
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"DamageDate":"2021-05-03",
"DamageKilometerreading":"213",
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":"1223",
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
The empty {} just contains more service types. Now when I send the request in Postman i get a 200 OK and when i debug i can see the following (sorry if the picture is blurry):
ยจ
However, my database does not get updated with these values. Here's the class for inserting data into the tables:
public async Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData)
{
bool CreateRequest = true;
int requestID = 0;
int claimID = 0;
//bool country = true;
//First Create the Request
foreach (Service item in model.Service)
{
//First Create the Request
if (CreateRequest)
{
var parameters = new DynamicParameters();
parameters.Add("WorkshopEmail", model.WorkshopEmail);
parameters.Add("WorkshopContactperson", model.WorkshopContactperson);
parameters.Add("WorkshopCellphone", model.WorkshopCellphone);
parameters.Add("DamageDate", model.DamageDate);
parameters.Add("LatestServiceDate", model.LatestServiceDate);
parameters.Add("LatestServiceKilometer", model.LatestServiceKilometer);
parameters.Add("DamageKilometerreading", model.DamageKilometerreading);
parameters.Add("CurrentKilometerreading", model.CurrentKilometerreading);
parameters.Add("CarOwnerDescription", model.CarOwnerDescription);
parameters.Add("WorkshopDiagnos", model.WorkshopDiagnos);
parameters.Add("AmountIncVat", model.AmountIncVat);
try
{
var requestIDenum = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[Request]
(WorkshopEmail,WorkshopContactperson,WorkshopCellphone,DamageDate,LatestServiceDate,
LatestServiceKilometer,DamageKilometerreading,CurrentKilometerreading,
CarOwnerDescription,WorkshopDiagnos,AmountIncVat)
VALUES
(#WorkshopEmail,#WorkshopContactperson,#WorkshopCellphone,#DamageDate,#LatestServiceDate,
#LatestServiceKilometer,#DamageKilometerreading,#CurrentKilometerreading,
#CarOwnerDescription,#WorkshopDiagnos,#AmountIncVat);SELECT SCOPE_IDENTITY();",parameters);
requestID = requestIDenum.First();
CreateRequest = false;
}
catch(Exception ex)
{
int hej = 0;
}
}
if (item.fileuploadresults != null)
{
foreach (FileUploadResult f in item.fileuploadresults)
{
var parameters = new DynamicParameters();
parameters.Add("file", f.filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
int FileMessageID = filemessage.First();
await _sqlconnection.QueryAsync<int>($#"INSERT INTO[dbo].[ClaimCrossOptionalFile]
(ClaimID,FileID)
VALUES
({claimID},{FileMessageID});");
}
}
return true;
//return list;
}
Controller:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
// if (!ModelState.IsValid)
// {
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
try
{
//await _request.AddRequest(request);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Interface:
Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData);
Sidenote: This is part of the code, as i've tried to keep it short, so perhaps some } or something is missing here, but there's no problem. If i should add the whole code i could perhaps send it in a link or something similar, as it would be a lot to upload here.
However, I do not now how to proceed with this issue at the moment. I've not worked with form-data much before, at least not with passing json as a value. Perhaps there's something I'm missing/have to do in the controller with the json data? I've tried looking for solutions but I've gotten stuck here. The only issue is that the database does not get updated.
Update, the model:
public class Work
{
//base for claim
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
public string id { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string quantity { get; set; } = "";
//service
public int rentreasonId { get; set; } = -1;
public int rentservicecartypeId { get; set; } = -1;
//tyres
public int tireserviceId { get; set; } = -1;
public IList<TireType> tireTypes { get; set; }
public IList<Labour> labours { get; set; }
public DateTime DateFrom{ get; set; } = DateTime.Parse("1753-01-01");
public DateTime DateTo { get; set; } = DateTime.Parse("1753-01-01");
//Insurance
public string totalAmount { get; set; }
public string requestInsuranceVatID { get; set; }
public string vat { get; set; } = "0.0";
public string totalExclVat { get; set; }="0.0";
public string totalIncVat { get; set; }="0.0";
}
public class Labour
{
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
}
public class TireType
{
public string quantity { get; set; } = "";
public string brand { get; set; } = "";
public string model { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string price { get; set; } = "";
public string tireTypeId { get; set; } = "";
public string widthID { get; set; } = "";
public string heightID { get; set; } = "";
public string diameterID { get; set; } = "";
}
public class Request
{
public string WorkshopEmail { get; set; } = "";
public string WorkshopContactperson { get; set; } = "";
public string WorkshopCellphone { get; set; } = "";
public int AmountIncVat { get; set; } = 0;
#region Claim
public DateTime DamageDate { get; set; } = DateTime.Parse("1753-01-01");
public DateTime LatestServiceDate { get; set; } = DateTime.Parse("1753-01-01");
public int LatestServiceKilometer { get; set; } = 0;
public int DamageKilometerreading { get; set; } = 0;
public int CurrentKilometerreading { get; set; } = 0;
public string CarOwnerDescription { get; set; } = "";
public string WorkshopDiagnos { get; set; } = "";
//public string OptionalMessage { get; set; } = "";
#endregion
public IList<Service> Service { get; set; }
}
public class TireTread
{
public string tireserviceId { get; set; } = "";
public string leftfront { get; set; } = "";
public string rightfront { get; set; } = "";
public string leftrear { get; set; } = "";
public string rightrear { get; set; } = "";
public string added1 { get; set; } = "";
public string added2 { get; set; } = "";
public string added3 { get; set; } = "";
public string added4 { get; set; } = "";
public string added5 { get; set; } = "";
}
public class TireMessage
{
public int tireserviceId { get; set; }
public string message { get; set; }
}
public class Service
{
// [JsonProperty("ServiceId")]
public string RequestTypeId { get; set; } = "";
public string CategoryId { get; set; } = "-1";
public string OptionalMessage { get; set; } = "";
public IList<Work> works { get; set; }
public IList<TireTread> treads { get; set; }
public IList<TireMessage> TireMessages { get; set; }
//filuppladdning
public IList<FileUploadResult> fileuploadresults { get; set; }
}
//filuppladdning
public class FileUploadResult
{
//public IFormFile files { get; set; }
public string filename { get; set; }
}
Firstly,the json format does not match the model structure.You need to pass json like this(Pay attention to DamageKilometerreading and LatestServiceKilometer,the type of them are int,so don't use ""):
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"DamageDate":"2021-05-03",
"DamageKilometerreading":213,
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":1223,
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
Then try to add public string service { get; set; }="" inService model.
I found a solution, in case anyone else comes across this problem. I needed to modify the controller and add this code:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
await _request.AddRequest(request, file, jsonData);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Basically adding request (that I deserialize in the begining of the method), and adding the file, and jsonData in an await request, solved the problem. As for the fileuploading, I needed to modify that method as well, to get the filename into the database:
if (file != null)
{
foreach (IFormFile f in file)
{
string filename = Path.GetFileName(f.FileName);
var parameters = new DynamicParameters();
parameters.Add("file", filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO
[dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
}
}
Changing these to made it possible to send a request containg both the json key value, and multiple files, in the same request.

Retrieve part of structured data from POCOs C#

I have a List<TerminalLink> from which I want to retrieve a subset of. See the class structure below.
The subset is defined by a "map" which identifies which ChannelLink to select in any given scenario. Multiple ChannelLinks may be required per scenario, perhaps from the same ChannelGroup, perhaps from different ChannelGroups on the same TerminalLink, and perhaps from multiple TerminalLinks in my original in memory list.
The ChannelLink can only be select if it's ChannelGroupLink and TerminalLink match too (they form part of the index, I guess).
I have tried various Linq and foreach approaches, but I'm running into tens of lines of code, which is ugly and difficult to follow. I'm sure there is an elegant approach.
How do I return a pruned List<TerminalLink> containing just the data that matches my map (i.e. containing only TerminalLinks and ChannelGroupLinks with required ChannelLinks)?
Class structure:
public class TerminalLink
{
public string TerminalName { get; set; }
public string TerminalType { get; set; }
public ChannelGroupLink[] ChannelGroups { get; set; }
}
public class ChannelGroupLink
{
public string GroupName { get; set; }
public int ItemType { get; set; }
public int SubType { get; set; }
public ChannelLink[] Channels { get; set; }
}
public class ChannelLink
{
public string ChannelName { get; set; }
public string PathName { get; set; }
public string DataType { get; set; }
public bool IsOutput { get; set; }
}
EDIT to include the latest attempt:
public static List<TerminalLink> GetCompatibleChannelLinks(List<TerminalLinkMap> terminalLinkMaps, List<TerminalLink> asBuiltList)
{
List<TerminalLink> matching = new List<TerminalLink>();
var terminalsWithSomeMatchingChannelGroups = from terminal in asBuiltList
from tlm in terminalLinkMaps
where terminal.TerminalType == tlm.ItemSubTypeName
from cgsMaps in tlm.ChannelGroupsToLink
from cgs in terminal.ChannelGroups
where cgsMaps.IsLinkMatch(cgs.GroupName, cgs.ItemType, cgs.SubType)
select (
link: new TerminalLink()
{
TerminalName = terminal.TerminalName,
TerminalType = terminal.TerminalType
},
original: terminal, map: tlm
);
foreach (var possibleLink in terminalsWithSomeMatchingChannelGroups)
{
var linkCandidate = possibleLink.link;
var originalData = possibleLink.original;
var map = possibleLink.map;
foreach (var cgs in originalData.ChannelGroups)
{
foreach (var channel in cgs.Channels)
{
// WIP
}
}
}
}
EDIT 2: inclusion of TeminalLinkMap
public class TerminalLinkMap
{
public string TerminalTypeName { get; set; }
public string ItemSubTypeName { get; set; } // Match on this.
public ChannelGroupToLink[] ChannelGroupsToLink { get; set; }
}
public class ChannelGroupToLink
{
public string GroupName { get; set; } // regex match is ok.
public int ItemType { get; set; }
public int SubType { get; set; }
public ChannelToLink[] Channels { get; set; }
public ChannelGroupToLink GetClone() => GetClone(this);
public bool IsLinkMatch(string groupName, int itemType, int subType)
{
return
GroupName == groupName
&& ItemType == itemType
&& SubType == subType;
}
}
public class ChannelToLink
{
public int ItemType { get; set; }
public string DataType { get; set; }
public int DataSizeInBits { get; set; }
public bool IsOutput { get; set; }
public ChannelToLink GetClone() => GetClone(this);
public bool IsLinkMatch(string dataType, bool isOutput)
{
return
DataType == dataType
&& IsOutput == isOutput;
}
public static ChannelToLink GetClone(ChannelToLink original) => new ChannelToLink()
{
ItemType = original.ItemType,
DataType = original.DataType,
DataSizeInBits = original.DataSizeInBits,
IsOutput = original.IsOutput
};
}
There is no need for a join.
Try following:
class Program
{
static void Main(string[] args)
{
List<TerminalLink> asBuiltList = new List<TerminalLink>();
List<TerminalLink> links = asBuiltList
.Select(x => new { TerminalLink = x, ChannelGroups = x.ChannelGroups.Where(y => y.IsLinkMatch("Apple", 123, 456)) })
.Where(x => x.ChannelGroups.Count() > 0)
.Select(x => new TerminalLink() { TerminalName = x.TerminalLink.TerminalName, TerminalType = x.TerminalLink.TerminalType, ChannelGroups = x.ChannelGroups.ToArray()})
.ToList();
}
}
public class TerminalLink
{
public string TerminalName { get; set; }
public string TerminalType { get; set; }
public ChannelGroupLink[] ChannelGroups { get; set; }
}
public class ChannelGroupLink
{
public string GroupName { get; set; }
public int ItemType { get; set; }
public int SubType { get; set; }
public ChannelLink[] Channels { get; set; }
public Boolean IsLinkMatch(string groupName, int itemType, int subType)
{
return (this.GroupName == groupName) && ( this.ItemType == itemType) && (this.SubType == subType);
}
}
public class ChannelLink
{
public string ChannelName { get; set; }
public string PathName { get; set; }
public string DataType { get; set; }
public bool IsOutput { get; set; }
}
}

C# sort datagridview on column header click

:)
I have a datagridview and I fill it by List (I get data from 2 text files), but when I tried to click on a column header (I tried with all columns headers), I can't sort my datagridview data. This is my code:
public class Data1
{
public string Campionato { get; set; }
public string Data { get; set; }
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public int HSHT { get; set; }
public int ASHT { get; set; }
public int HSSH { get; set; }
public int ASSH { get; set; }
}
public class Data2
{
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public string HODD { get; set; }
public string XODD { get; set; }
public string AODD { get; set; } //no name in sample
public string Data { get; set; }
public string RisFin { get; set; } //no name in sample
public string Over05SH { get; set; }
public string Over05HT { get; set; }
public string Over15HT { get; set; }
public string Over05FT { get; set; }
public string Over15FT { get; set; }
public string Over25FT { get; set; }
public string Over35FT { get; set; }
public string Over45FT { get; set; }
}
public class CombinedData
{
public string Campionato { get; set; }
public string Data { get; set; }
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public int HSHT { get; set; }
public int ASHT { get; set; }
public int HSSH { get; set; }
public int ASSH { get; set; }
public string HODD { get; set; }
public string XODD { get; set; }
public string AODD { get; set; } //some name
public string RisFin { get; set; } //no name in sample
public string Over05SH { get; set; }
public string Over05HT { get; set; }
public string Over15HT { get; set; }
public string Over05FT { get; set; }
public string Over15FT { get; set; }
public string Over25FT { get; set; }
public string Over35FT { get; set; }
public string Over45FT { get; set; }
}
var data1 = File.ReadAllLines("read" + campionatoselezTxt.Text + "stats.txt").ToList();
var data2 = File.ReadAllLines("read" + campionatoselezTxt.Text + "bex.txt").ToList();
var dataList1 = new List<Data1>();
foreach (var data in data1)
{
var columns = data.Split(';');
dataList1.Add(new Data1
{
Campionato = columns[0],
Data = columns[1],
Home = columns[2],
Away = columns[3],
HSFT = int.Parse(columns[4]),
ASFT = int.Parse(columns[5]),
HSHT = int.Parse(columns[6]),
ASHT = int.Parse(columns[7]),
HSSH = int.Parse(columns[8]),
ASSH = int.Parse(columns[9])
//other int properties
});
}
var dataList2 = new List<Data2>();
foreach (var data in data2)
{
var columns = data.Split(';');
dataList2.Add(new Data2
{
Home = columns[0],
Away = columns[1],
HODD = columns[4],
XODD = columns[5],
AODD = columns[6],
});
}
var combinedDataList = from d1 in dataList1
//join d2 in dataList2 on d1.Home equals d2.Home
join d2 in dataList2 on new { d1.Home, d1.Away } equals new { d2.Home, d2.Away }
select new CombinedData
{
Campionato = d1.Campionato,
Data = d1.Data,
Home = d2.Home,
Away = d2.Away,
HSFT = d1.HSFT,
ASFT = d1.ASFT,
HSHT = d1.HSHT,
ASHT = d1.ASHT,
HSSH = d1.HSSH,
ASSH = d1.ASSH,
HODD = d2.HODD,
XODD = d2.XODD,
AODD = d2.AODD,
RisFin = d2.RisFin,
Over05SH = d2.Over05SH
}; //map all properties
finabexDgv.DataSource = combinedDataList.ToList();
finabexDgv.AllowUserToOrderColumns = true;
I'd like to have a possibility to sort by clicking columns headers.
I need your advices, please :)
Happy Sunday!
On your desing view, search the "ColumnHeaderMouseClick" and double click on the empty field.
on the new function, apply some code like this:
dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgv.Columns[e.ColumnIndex].SortMode != DataGridViewColumnSortMode.NotSortable)
{
if (e.ColumnIndex == newSortColumn )
{
if (newColumnDirection == ListSortDirection.Ascending)
newColumnDirection = ListSortDirection.Descending;
else
newColumnDirection = ListSortDirection.Ascending;
}
newSortColumn = e.ColumnIndex;
switch (newColumnDirection)
{
case ListSortDirection.Ascending:
dgv.Sort(dgv.Columns[newSortColumn], ListSortDirection.Ascending);
break;
case ListSortDirection.Descending:
dgv.Sort(dgv.Columns[newSortColumn], ListSortDirection.Descending);
break;
}
}
}
and at the top of the class, add two private variables:
int newSortColumn;
ListSortDirection newColumnDirection = ListSortDirection.Ascending;
This will work if you don't have anything else rare at your source code.
Note: This code is not mine, i got it form here at stackoverflow

NullReferenceException attempting to access a list located in a class?

I am attempting to retrieve information using the Steam API. I created the classes offerStuff and itemsClass, offerStuff contains public List<itemsClass> items { get; set; }, however, whenever I attempt to access this list through os.items.Add(item), my program crashes with NullReferenceException. Is there some declaration I am missing? If so, how would I declare it so I can access it without the exception?
public static List<offerStuff> pollOffers()
{
using (dynamic tradeOffers = WebAPI.GetInterface("IEconService", config.API_Key))
{
List<offerStuff> OfferList = new List<offerStuff>();
offerStuff os = new offerStuff();
KeyValue kvOffers = tradeOffers.GetTradeOffers(get_received_offers: 1);//, active_only: 1
foreach (KeyValue kv in kvOffers["trade_offers_received"].Children)
{
os.tradeofferid = kv["tradeofferid"].AsInteger(); ;
os.accountid_other = Convert.ToUInt64(kv["accountid_other"].AsInteger());
os.message = kv["message"].AsString();
os.trade_offer_state = kv["trade_offer_state"].AsInteger();
foreach (KeyValue kv2 in kv["items_to_receive"].Children)
{
itemsClass item = new itemsClass();
item.appid = (kv2["appid"].AsInteger());
item.assetid = kv2["assetid"].AsInteger();
item.classid = kv2["classid"].AsInteger();
item.instanceid = kv2["instanceid"].AsInteger();
item.amount = kv2["amount"].AsInteger();
item.missing = kv2["missing"].AsInteger();
os.items.Add(item);
}
os.is_our_offer = kv["is_our_offer"].AsBoolean();
os.time_created = kv["time_created"].AsInteger();
os.time_updated = kv["time_updated"].AsInteger();
OfferList.Add(os);
}
return OfferList;
}
}
}
public class offerStuff
{
public int tradeofferid { get; set; }
public SteamID accountid_other { get; set; }
public string message { get; set; }
public int trade_offer_state { get; set; }
public List<itemsClass> items { get; set; }
public bool is_our_offer { get; set; }
public int time_created { get; set; }
public int time_updated { get; set; }
}
public class itemsClass
{
public int appid { get; set; }
public int assetid { get; set; }
public int classid { get; set; }
public int instanceid { get; set; }
public int amount { get; set; }
public int missing { get; set; }
}
The problem is probably that you're not initializing the collection items. You could do it on your contructor like this
public offerStuff()
{
items = new List<itemsClass>();
}

Adding index field to LINQ List <T> results using C#

I'm using a generic list. For example (with some properties):
public class randomList
{
public string propertyA { get; set; }
public string propertyB { get; set; }
public string propertyC { get; set; }
}
So on my retrieving query I used to write the following:
_grouppedResto.Select((value, index) => new { index = index, value = value });
dgvHeader.DataSource = _grouppedResto;
But now it shows blank on index column. I will like to get something like this :
this is all about the datagrid :
this.dgvHeader.AllowUserToAddRows = false;
this.dgvHeader.AllowUserToDeleteRows = false;
this.dgvHeader.AllowUserToResizeRows = false;
this.dgvHeader.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvHeader.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.FECRGV,
this.TDORGV,
this.NDORGV,
this.RUCCLI,
this.RAZCLI,
this.VVTRGVS,
this.IGVRGVS,
this.TOTRGVS,
this.TCARGV,
this.VVTRGVD,
this.IGVRGVD,
this.TOTRGVD});
this.dgvHeader.Location = new System.Drawing.Point(12, 128);
this.dgvHeader.Name = "dgvCACD";
this.dgvHeader.Size = new System.Drawing.Size(1265, 611);
this.dgvHeader.TabIndex = 13;
**dgvHeader.AutoGenerateColumns = false;**
How can I resolve this?
It looks like you need to assign _grouppedResto to an anonymous type as in:
var yourSequence = _groupedResto.Select((value, index) => new { index = index, value = value });
dgvHeader.DataSource = yourSequence;
I'd be happy to help with any particulars you care to provide.
Good luck, hope this helped :)
To combine the index with the properties of your list element you need to change your select statement into something like this:
_grouppedResto.Select(
(value, index) => new {
index = index, propertyA = value.propertyA, propertyB = value.propertyB
}
);
Well, I use this way to solve this... (I think is the worst way, cause you have to modified the domain class)
public class RGVCAFAC
{
public int index { get; set; }
public string CODEAUX { get; set; }
public string FECRGV { get; set; }
public string TDORGV { get; set; }
public string MONRGV { get; set; }
public string NDORGV { get; set; }
public string RUCCLI { get; set; }
public string RAZCLI { get; set; }
public string CDCRGV { get; set; }
public string TERRGV { get; set; }
public string PDSRGV { get; set; }
public double VVTRGVS { get; set; }
public double IGVRGVS { get; set; }
public double TOTRGVS { get; set; }
public string TCARGV { get; set; }
public double VVTRGVD { get; set; }
public double IGVRGVD { get; set; }
public double TOTRGVD { get; set; }
public string PACEST { get; set; }
public string CODUNI { get; set; }
public string DIRCLI { get; set; }
public string TELCLI { get; set; }
public int PFLAG { get; set; }
//I have to add the following, so generators are useless :(
public RGVCAFAC()
{
}
public RGVCAFAC(RGVCAFAC x)
{
this.CODEAUX = x.CODEAUX;
this.FECRGV = x.FECRGV;
this.TDORGV = x.TDORGV;
this.MONRGV = x.MONRGV;
this.RUCCLI = x.RUCCLI;
this.RAZCLI = x.RAZCLI;
this.CDCRGV = x.CDCRGV;
this.TERRGV = x.TERRGV;
this.PDSRGV = x.PDSRGV;
this.VVTRGVS = x.VVTRGVS;
this.IGVRGVS = x.IGVRGVS;
this.TOTRGVS = x.TOTRGVS;
this.TCARGV = x.TCARGV;
this.VVTRGVD = x.VVTRGVD;
this.IGVRGVD = x.IGVRGVD;
this.TOTRGVD = x.TOTRGVD;
this.PACEST = x.PACEST;
this.CODUNI = x.CODUNI;
this.DIRCLI = x.DIRCLI;
this.TELCLI = x.TELCLI;
this.PFLAG = x.PFLAG;
}
}
and finally :
var yourSequence = _grouppedResto.
Select((value, index) => new RGVCAFAC(value) { index = index+1, rgvcafac = value }).ToList(); //need to begin on 1 not on 0
dgvCabecera.DataSource = yourSequence;
int theIndex = 1;
foreach(var x in _grouppedResto)
{
x.index = theIndex;
theIndex += 1;
}

Categories