【问题标题】:How to do custom binding of listview datasource in asp.net?如何在asp.net中对listview数据源进行自定义绑定?
【发布时间】:2017-03-02 05:59:51
【问题描述】:

我有一个列表视图数据源,它从表中获取数据,其中包含角色 ID、名字、姓氏、手机号码。 我有另一个表将 roleId 与角色名称映射。

在 asp.net 表单中,我已将数据源绑定到检索角色 ID、名字和姓氏的表。我正在使用后端编程来做到这一点。

我的问题是,如何在列表视图中显示角色名称而不是角色 ID。

我的后端代码是这样的

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindListView();
    }
}

private void BindListView()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT roleId, fName, lname,mobilenumber Country FROM Admin";
            cmd.Connection = con;
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                lvCustomers.DataSource = dt;
                lvCustomers.DataBind();
            }
        }
    }
}

显然,这会返回整数角色 ID,现在我想显示角色名称而不是角色 ID。我可以从将roleID 与rolename 映射的roletable 中获取rolename。

【问题讨论】:

    标签: c# asp.net listview


    【解决方案1】:

    在您的 SQL 中使用内部联接,如下所示。这是一个简单的修复,而不是在获取数据后更新 DataTable。

    "SELECT roleName, fName, lname,mobilenumber Country FROM Admin A Inner join RoleTable R on A.roleID = R.roleID";

    【讨论】:

    • 如果允许使用 LINQ。您可以尝试这样的 var results = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"] select new { CustID = (int)table1["CustID"], ColX = (int)table1["ColX"], ColY = (int)table1["ColY"], ColZ = (int)table2["ColZ"] };
    猜你喜欢
    • 2010-10-09
    • 2010-09-13
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2019-05-28
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多