我有一个ID清单。这些是答案ID。我在申请表中持有一份清单。我只想向SQL Server发出请求以获取与ID匹配的答案。
我需要在C#中使用foreach循环吗?如何合并结果到数据表或其他内容?我需要一些帮助。
我想在ASP.NET项目中使用C#获取数据。
编号清单<List>
::
answer_id
---------
5
4
23
2
45
16
我想使用C#并显示在数据表中:(预期结果)
answer_id answer
-------------------------------------
5 It's true
4 Maybe next time
23 Man this is crazy
2 Can i help you?
45 Wtf..
16 I can not believe..
如果匹配,我们的选择查询必须返回答案。在此示例中,假设我们找到了所有答案。
简单查询一个结果:
SELECT answer_id, answer
FROM answers
WHERE answer_id = 5
结果:
answer_id answer
-----------------------
5 It's true
假设您正在使用ADO.NET,则需要创建一个包含answer_id和answer属性的类。在我的示例中,我的行为好像是一个名为Answer的类具有这些值。然后,我首先创建一个DataAccess类,如下所示:
public static class DataAccess
{
private static string reportConnectionString = "Data Source=;Initial Catalog=;Persist Security Info=;User ID=;Password=";
public static class Answer
{
public int AnswerID {get; set;}
public string Answer {get; set;}
}
public static bool GetRecords(int AnswerId, out List<Answer> lstAnswers, out string sMessage)
{
lstAnswers = new List <Answer>();
AnswerID;
sMessage = "";
try
{
using(SqlConnection connection = new SqlConnection(reportConnectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("@id", AnswerID);
command.CommandText = @"select answer_id, answer from answers where answer_id = @id";
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows == false)
{
sMessage = "Could not find data";
return false;
}
while(reader.Read())
{
Answer answer= new Answer();
answer.answer_id= reader.GetInt32(reader.GetOrdinal("answer_id"));
answer.answer= reader.GetValue(reader.GetOrdinal("answer")).ToString();
// -- Adding single object to list
lstAnswers.Add(log);
}
}
}
}
return true;
}
catch (Exception exc)
{
sMessage = exc.ToString();
return false;
}
}
}
如果您有一个answer_id列表,则可以创建一个foreach循环来遍历该列表,并连接answer_id和要显示的答案。
foreach (var item in lstAnswers)
{
txtTextBox.Text = item.answer_id + " " + item.answer;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句