gpt4 book ai didi

c# - asp.net 从 List<> 方法获取值

转载 作者:行者123 更新时间:2023-11-30 20:28:52 25 4
gpt4 key购买 nike

我有一个数据访问类,它有 List<> 类型的方法。其中数据完全来自 SQL 服务器,但我需要通过迭代 List<> 数据在我的 ASP GridView 中显示它。这是我的数据访问层。

   public class AdminPanelDataAccessLayer
{
public List<PersonalInformation> GetAllPersonalInfo()
{
List<PersonalInformation> listsPersonalInfo = new List<PersonalInformation>();
string connString = ConfigurationManager.ConnectionStrings["HRMS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("usp_GetApplicantCNICAndName", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
PersonalInformation pi = new PersonalInformation();
pi.CNIC = reader["CNIC"].ToString();
pi.Name = reader["Name"].ToString();


listsPersonalInfo.Add(pi);

}
return listsPersonalInfo;

}
}
}

这是通过迭代在GridView中显示数据的方法。

        private void GetAllData()
{
AdminPanelDataAccessLayer apdal = new AdminPanelDataAccessLayer();
List<PersonalInformation> pi = apdal.GetAllPersonalInfo();

DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("CNIC", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

foreach (object item in pi)
{
dr = dt.NewRow();
dr["CNIC"] = pi.Select(o => o.CNIC);
dr["Name"] = pi.Select(o => o.Name);
dt.Rows.Add(dr);
}

ViewState["CurrentTable"] = dt;

GridView2.DataSource = dt;
GridView2.DataBind();
}

请指导我实现我的目标。

最佳答案

将字段添加到您的 aspx 中的网格中:

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
<asp:BoundField DataField="CNIC" />
<asp:BoundField DataField="Name" />
</asp:GridView>

你的代码背后:

private void GetAllData()
{
AdminPanelDataAccessLayer apdal = new AdminPanelDataAccessLayer();
List<PersonalInformation> pi = apdal.GetAllPersonalInfo();

//remove any records here, i am just removing first element here
if (pi.Count > 0)
pi.RemoveAt(0);

GridView2.DataSource = pi ;
GridView2.DataBind();
}

关于c# - asp.net 从 List<> 方法获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46816968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com