Reputation: 137
i have a data contract defined as follows:
[DataContract]
public class DemoSearchList : ReturnValuesBase
{
[DataMember]
public string SessionId { get; set; }
[DataMember]
public string[] StartDate { get; set; }
[DataMember]
public string[] EndDate { get; set; }
[DataMember]
public string ProductID { get; set; }
}
as u can observe StartDate and Enddate are array of strings. i want to send array of responses to these.
for (int i = 0; i < DS.Tables[0].Rows.Count; i++)
{
DemoSearchList.StartDate[i] = Convert.ToString(DS.Tables[0].Rows[i][0]);
DemoSearchList.EndDate[i] = Convert.ToString(DS.Tables[0].Rows[i][1]);
}
DS is a dataset. but i get an error as index out of bound . can anyone please help and also tel me if anything extra needs to be declared and used to achieve this
Upvotes: 0
Views: 2176
Reputation: 9947
For using Array
their length should be defined
StartDate = new String[10]; //can use data row count here
EndDate = new String[10]; //can use data row count here
if you want to use objects of dynamic length
then use LIST
instead
or change them to
[DataMember]
public List<String> StartDate { get; set; }
[DataMember]
public List<String> EndDate { get; set; }
Upvotes: 0
Reputation: 4727
This means that your array is has not the correct size or is not yet initialized. You need to do this before your for-loop:
DemoSearchList.StartDate = new string[DS.Tables[0].Rows.Count];
DemoSearchList.EndDate = new string[DS.Tables[0].Rows.Count];
But I would prefer to make a list instead of an array (if you don't need the index of each value):
[DataContract]
public class DemoSearchList : ReturnValuesBase
{
public DemoSearchList()
{
this.StartDate = new List<string>();
this.EndDate = new List<string>();
}
[DataMember]
public List<string> StartDate { get; set; }
[DataMember]
public List<string> EndDate { get; set; }
}
Then your for-loop could look like this:
for (int i = 0; i < DS.Tables[0].Rows.Count; i++)
{
DemoSearchList.StartDate.Add(Convert.ToString(DS.Tables[0].Rows[i][0]));
DemoSearchList.EndDate.Add(Convert.ToString(DS.Tables[0].Rows[i][1]));
}
Upvotes: 1