I want to get an property value from an object that is in a list and put it into textbox.text
Below i have an example of my code:
The object:
public class Incident
{
public int Incident_id { get; set; }
public string Description { get; set; }
public string Caller { get; set; }
}
Below is my code in my form class:
List<Incident> incidentById = new List<Incident>();
incidentById = db.GetIncidentById(ID);
when my list is filled i want to put the string Caller into an textbox somewhat like below:
textBoxCaller.Text = incidentById[1].Caller;
I'm stuck at this point so i hope someone can help me out.
Thanks!
EDIT:
public List<Incident> GetIncidentById(int id)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("IncidentLog")))
{
var output = connection.Query<Incident> ($"select * from Incidents where Incident_id like #id", new { id = "%id%" }).ToList();
return output;
}
}
I wasn't passing the right value into my query
this did the trick!
What you want is $"select * from Incidents where Incident_id = #id", new { id }
do you want first value should go?
check like.
if(incidentById.Count>0)
{
textBoxCaller.Text = incidentById.First().Caller;
}
// or you can join all Caller in list like
if(incidentById.Count>0)
{
textBoxCaller.Text = string.join(",",incidentById.Select(x=>x.Caller));
}
The issue that you are facing is that you are trying to access the second element in the list when there are not two or more elements in the list. If you are trying to access the first element in the list, then you could do either
textBoxCaller.Text = incidentById[0].Caller;
or
textBoxCaller.Text = incidentById.First().Caller;
If you do in fact want the second element of the list, then you should be checking to verify that it's length is at least two:
if(incidentById.Count >= 2)
{
...
}
Finally, as mentioned in a comment, you should rename GetIncidentById to something that makes clear it is returning a list, like GetIncidentsById or something similar.
Related
I have a class which populates without a problem from a rest server and it binds
the class is
namespace SavRMobile.AccessToken
{
public class AccessTokenModel
{
public User user { get; set; }
}
public class User
{
public Accesstoken[] accessTokens { get; set;}
}
public class Accesstoken
{
public string appId { get; set; }
public string value { get; set; }
}
}
there will only ever be 1 token that i need to retrieve. I dont know why the developers made it into a list? anyways i want to access the accesstoken.value property.. it get returned as an array.. I cant seem to get the value even in a foreach it will not let me. or should i just grad the index of [0] but not sure what the approach is?
You can try like this:
AccessTokenModel receivedAccessTokens = new AccessTokenModel();
if (receivedAccessTokens.user.accessTokens.Length > 0)
{
string appID = receivedAccessTokens.user.accessTokens[0].appId;
string value = receivedAccessTokens.user.accessTokens[0].value;
}
In the definition of the class accessTokens is defined as an array of Accesstoken so you have to access their values based on the index. It is always better to check for the Array Length/items count before accessing a value based on the index. so above code will do that checking as well as retrieving the values for appId and value.
You can call it like this:
if(RecievedAccessToken.User.accessTokens.Length > 0)
{
ReceivedAccessToken.User.accessTokens[0].value;
}
Hope it helps!
Get spesific Index value
if(recievedAccessToken.User.Accesstoken.Length > 0)
{
recievedAccessToken.User.Accesstoken[0].value
}
or
//Check `length`
AccessTokenModel tokens = recievedAccessToken.User.Accesstoken[0];
Return result List
AccessTokenModel receivedAccessTokens = new AccessTokenModel();
foreach (AccessTokenModel act in recievedAccessToken)
{
receivedAccessTokens.Add(act);
}
I am trying to populate a list of a custom class using the AddRange method.
Here is the custom class:
public class Hook
{
public Hook(System.Data.DataRow values)
{
this.text = values[0].ToString();
this.category = values[1].ToString();
this.weather = values[2].ToString();
this.timeofday = values[3].ToString();
}
public string text { get; set; }
public string category { get; set; }
public string[] associatedLandmarks { get; set; }
public string weather { get; set; }
public string timeofday { get; set; }
}
Here is my object array that I need to filter objects from, I am populating it using values from a datatable:
int numberofhooks = result.Tables[1].Rows.Count - 1;
Hook[] Hooks = new Hook[numberofhooks];
for (int i = 0; i < numberofhooks; i++)
{
Hooks[i] = new Hook(result.Tables[1].Rows[i]);
}
I need to filter out a subset of these objects using a variable that gets updated on the fly, which is a property of the class.
'category' is the property
I am using the AddRange method to do this, but it isn't working. What can be the issue with this? Or is there another way to accomplish this?
List<Hook> RelevantHooks = new List<Hook>();
foreach (string category in relevantHookCategories)
{
RelevantHooks.AddRange(from item in Hooks
where item.category == category
select item);
}
Thanks
I see two problems here:
If you want all the rows from your table why are you using:
int numberofhooks = result.Tables[1].Rows.Count - 1;
It should be:
int numberOfHooks = result.Tables[1].Rows.Count;
Perhaps the last item that you are excluding has the category you are looking for.
When you say "on the fly" I'm assuming that you want to have the subset RelevantHooks updated even after your query, when modifying Hooks, if that's the case then you don't have to use a List, just define your relevantHooks as:
IEnumerable<Hook> relevantHooks = Hooks.Where(h => relevantHookCategories.Contains(h.category));
e.g. If you modify the category property for any of Hooks items:
Hooks[0].category="Other Category Value";
Will either exclude or include the first hook from relevantHooks
RelevantHooks.AddRange(Hooks.Where(hook => category == hook.category));
should be enough. You don't necessarily need the select clause in this case.
No need to use AddRange. Just iterate Hooks once and check if it's one of the categories.
RelevantHooks = Hooks.Where(h => relevantHookCategories.Contains(h.category)).ToList();
Try this:
RelevantHooks.AddRange((from item in Hooks
where item.category == category
select item).ToArray());
I don't think it should matter, but it could be the AddRange method is failing because it's being passed IQueryable when it is expecting IEnumerable
Given my last Comment, here's what I meant:
for (int i = 0; i < numberofhooks; i++)
{
Hooks[i] = new Hook(result.Tables[1].Rows[i]);
if(relevantHookCategories.Contains(Hooks[i].category)
RelevantHooks.Add(Hook[i]);
}
OK, so I have learned how to create a list, view items in the list, and use the items in the list. I now want to learn how to edit the information that is in the list.
Here is my list:
class ObjectProperties
{
public string ObjectNumber { get; set; }
public string ObjectComments { get; set; }
public string ObjectAddress { get; set; }
}
List<ObjectProperties> Properties = new List<ObjectProperties>();
This is how I am adding values to the list:
ObjectProperties record = new ObjectProperties
{
ObjectNumber = txtObjectNumber.Text,
ObjectComments = txtComments.Text,
ObjectAddress = addressCombined,
};
Properties.Add(record);
I am wanting the user to enter which number they want to update by using a textbox(txtUpdateObjectNumber). I then want to compare that number to the values that are stored in record.ObjectNumber and then if it exist I want to replace the information in record.ObjectNumber and record.ObjectComments where record.ObjectNumber == txtUpdateObjectNumber. If you need me to elaborate on anything just let me know. Any help would be appreciated. Thank You :)
To find the list item, use linq:
ObjectProperties opFound = Properties.Find(x => x.ObjectNumber == txtUpdateObjectNumber.Text);
Or the delegate form:
ObjectProperties opFound = Properties.Find(delegate (ObjectProperties x) { return x.ObjectNumber == txtUpdateObjectNumber.Text; });
Once you've found the item in the list, any changes you make to opFound, including the ObjectNumber, will persist in the list.
I have a class
public class Orders
{
public Orders() {}
private string _idOrder;
private string _totalPrice;
public string idOrder
{
get{ return _idOrder;}
set { _idOrder = value;}
}
public string totalPrice
{
get { return _totalPrice; }
set { _totalPrice = value; }
}
}
I am loading the list from database like this
while (dr.Read())
{
Orders.idOrder = dr["IdOrder"].ToString();
Orders.totalPrice= dr["totalPrice"].ToString();
}
It's is showing me only last record. How can I load all the orders and retrieve them back by foreach loop?
Create a list :-)
List<Order> orders = new List<Order>();
while (dr.Read())
{
Order order = new Order();
order.idOrder = dr["IdOrder"].ToString();
order.totalPrice= dr["totalPrice"].ToString();
orders.Add(order);
}
As you see, I renamed your class from Orders to Order, because that's what it really represents: One order. To have more orders, you need to put those single orders into a list.
It's only showing you the one item, because you're only changing properties on the one item, not instantiating a new one:
var results = new List<Order>();
while (reader.Read())
{
var order = new Order
{
Id = (int)reader["IdOrder"],
TotalPrice = (decimal)reader["totalPrice"]
};
results.Add(order);
}
I think you are looking for something like this:
IEnumberable<Order> FetchOrders()
{
while(dr.Read())
yield return new Order {
idOrder=dr["IdOrder"].ToString(),
totalPrice=dr["totalPrice"].ToString()
});
}
That Orders class represents a single order! If what you need is a list of orders then I suggest you rename that class to Order, and then create a List<Order> (a list of order-objects) and populate that from your query results.
Also (forgive me for being pernickety) "idOrder" is not a good field name. The standard approaches are "orderId" or just plain old "Id" (ID, or even id). Likewise I would expect the price-of-ONE-order to be called just "amount", or even "price"... not "totalPrice"... it'll be too confusing when you come to total-up the totalPrices... get my drift?
Cheers. Keith.
I don't see how that will compile. Orders.idOrder is not a static property, it's an instance property.
If i understand you right you want to use something like this:
List<Order> = new List<Order>();
while (dr.Read())
{
Order newOrder = new Order();
newOrder.idOrder = dr["IdOrder"].ToString();
newOrder.totalPrice= dr["totalPrice"].ToString();
orderList.Add(newOrder);
}
Notice this that I just discuss more for #Grook Answer. I Think it is so near to what to want.
IEnumberable<Order> FetchOrders()
{
while(dr.Read())
yield return new Order {
idOrder=dr["IdOrder"].ToString(),
totalPrice=dr["totalPrice"].ToString()
});
}
Then You can easily use foreach loop
Foreach(Order order in GetOrders())
{
doSomething(order);
}
Is it clear?
I have a c# object (below) that I'm trying to send to my javascript.
My problem is, that while I can iterate over the items in the list, I can't get to the string-property ('Period').
Referencing the object in JS shows no property at all. After Json-encoding in c#, I can still see the property just before returning it to caller (hovering over the result variable in below function):
[OutputCache(Duration = 0, VaryByParam = "None")]
public JsonResult GetRankingList() {
Response.ContentType = "text/javascript";
var user = _userService.GetUserByPrincipal(User);
// Note, we do this while the user waits as we need to make progress in repeated calls to get the compared ranking list.
_businessLogicServiceMaintenance.PerformMaintenanceSteps();
//TODO: Replace with userid (Guid)
var rankingList = _presenterService.GetRankingListForDisplay(user);
if (rankingList == null)
return Json("");
var result = Json(rankingList);
return result;
}
How on earth can I get past this? Any comments appreciated!
Yours, Anders, Denmark,
public class RankingListForDisplay : List<RankingListLine>
{
public string Period { get; set; }
}
Thanks for taking your time - I found a solution.
I changed above implementation of RankingListForDisplay to the one below. For some reason json likes it way better ;-)
public class RankingListForDisplay
{
public List<RankingListLine> Lines { get; set; }
public string Period { get; set; }
public RankingListForDisplay()
{
Lines = new List<RankingListLine>();
Period = "<Unspecified>";
}
}