public ArrayList ChequeACpayee(string Payee, DateTime Date)
{
ArrayList arr = new ArrayList();
try
{
con.Open();
SqlCommand cmd = new SqlCommand("ViewChequeforAcPayee", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = new SqlParameter();
p = cmd.Parameters.AddWithValue("@PayeeName", Payee);
p = cmd.Parameters.AddWithValue("@Date", Date);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ChequeInfo infoCheque = new ChequeInfo();
infoCheque.AcPayee = dr["AcPayee"].ToString();
arr.Add(infoCheque);
}
dr.Close();
con.Close();
}
catch (Exception e)
{
}
return arr;
}
ArrayList ArrAcpayee = ChequeAcPayee.ChequeACpayee (DDLPayee.SelectedItem.ToString(), BDPSelectDate.SelectedDate);
如何从此arraylist中获取单个值?该值必须转换为字符串。
答案 0 :(得分:7)
您可以使用索引器和强制转换:
string payee = (string) ArrAcpayee[0];
但你应该先检查尺寸:
if (ArrAcpayee.Length != 1)
{
// Create your own more appropriate exception
throw new SomethingWentWrongException("Expected 1 payee entry; got "
+ ArrAcpayee.Length);
}
string payee = (string) ArrAcpayee[0];
但是,我担心代码的其他方面:
List<T>
的框架?ChequeACpayee
方法中有多个结果?如果没有,那么该方法应返回一个字符串,如果没有一个结果则抛出using
语句来关闭数据库连接和数据读取器,而不是手动调用Close()
。否则,如果抛出异常,您将泄漏连接。答案 1 :(得分:1)
假设你正在使用linq:
ArrayList ArrAcpayee = ChequeAcPayee.ChequeACpayee (DDLPayee.SelectedItem.ToString(), BDPSelectDate.SelectedDate);
return ArrAcpayee.Cast<string>().Single(); //If there will always be just one value in the array list
return ArrAcpayee.Cast<string>().SingleOrDefault(); //If there will be either one or no value in the array list
return ArrAcpayee.Cast<string>().First(); //If you want to return the first value
希望这有帮助
答案 2 :(得分:0)
SqlDataReader中有一些构建方法可以让你这样做:
博士GetString(DR GetOrdinal( “AcPayee”)。);