简体   繁体   中英

JSON data List to combo box

I know this has been asked quite a few times and I know ot will be really simple but I'm really new to C# and I'm pulling my hair out because I've been coding (not very well) through the night. I have a class ProcessOrdersActive that I Deserialiaze to details . It's falling over when I try to add ProcessOrderNbr[I] to the combobox.

//Deserialise data 
ProcessOrdersActive details = JsonConvert.DeserializeObject<ProcessOrdersActive>(responseBody);

var ordersList = new List<ProcessOrdersActive>();
ordersList.Add(details);
int numofitems = ordersList.Capacity;
txtActiveOrders.Text = numofitems.ToString();

for (int i = 0; i < numofitems; i++)
{
     comboBoxOrders.Items.Add (details.ProcessOrderNbr[i]);
}    

You are trying to access an index that may be out of bounds of the array/list.

The number of items should be the Length/Count of the array/List you are accessing.

//Deserialise data 
ProcessOrdersActive details = JsonConvert.DeserializeObject<ProcessOrdersActive>(responseBody);

var ordersList = new List<ProcessOrdersActive>(); 
ordersList.Add(details); 
int numofitems = details.ProcessOrderNbr.Count;//If this is a list use Count. If it is an array use Length 
txtActiveOrders.Text = numofitems.ToString();

for (int i = 0; i < numofitems; i++) {
     comboBoxOrders.Items.Add (details.ProcessOrderNbr[i]); 
}

Many thanks for the responses. I had a good chat with a proficient C# programmer today and here is the solution that he came to. The names are slightly different from the original post.

//Deserialise data & send to DataGrid
ProcessOrderDetails details = JsonConvert.DeserializeObject<ProcessOrderDetails>(responseBody);
//Get number of operations and display to screen
int numofitems = details.MaterialList.Count<Materiallist>();
txtNumOfMaterials.Text = numofitems.ToString();
//Find the last operation
var lastone = details.MaterialList.Last<Materiallist>();
//Create a new material/operation list
var materialList = new List<Materiallist>();
//Add the last operation to the list
materialList.Add(lastone);
//Parse the list to the data grid
dataGridProcessOrderDetails.DataSource = materialList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM