使用CodeBehind从DataTable填充DropDownList

4
如何从代码后台使用DataTable设置下拉列表?
<asp:GridView ID="gvTemplateFields"
                runat="server"
                CssClass="grid"
                AutoGenerateColumns="false"

    <Columns>
        <asp:TemplateField HeaderText="Estado" ItemStyle-Width="50px">
            <ItemTemplate>
                <asp:DropDownList ID="RiskWorkDropDownList" runat="server">
                    <asp:ListItem Value="1">Pendiente</asp:ListItem>
                    <asp:ListItem>Atendido</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>                
    </Columns>

    <EmptyDataTemplate>No off-site links found.</EmptyDataTemplate>

</asp:GridView>

背后的代码:

public int SWMSTemplateId;
public DropDownList RiskWorkDropDownList;

protected void Page_Load(object sender, EventArgs e)
{
    SWMSTemplateId = int.Parse(Request.QueryString["templateid"]);

    DataTable templateFields = SWMSField.GetTemplateFields(SWMSTemplateId);

    RiskWorkDropDownList.DataSource = templateFields;
    RiskWorkDropDownList.DataBind();

}

错误:

System.NullReferenceException: Object reference not set to an instance of an object.

RiskWorkDropDownList 为空

RiskWorkDropDownList.DataSource = templateFields;

我正在尝试使它像这个问题/答案那样工作:

DropdownList DataSource


1
展示一下你目前为止尝试编写的代码,这样回答问题的人就不必从头开始写了。 - mason
哪一行出现了错误?哪个对象为空?你知道什么是NullReferenceException吗? - mason
4个回答

1

像这样简单的代码应该能帮到你:

C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable theTable = new DataTable();
            theTable.Columns.Add("Names", typeof(string));
            theTable.Rows.Add("Name1");
            theTable.Rows.Add("Name2");
            theTable.Rows.Add("Name3");

            for (int i = 0; i < theTable.Rows.Count; i++ )
            {
                string theValue = theTable.Rows[i].ItemArray[0].ToString();
                DropDownList1.Items.Add(theValue);
            }

        }
    }
}

ASP

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>

我能不能只是使用类似DataBind()这样的东西? - el_pup_le
1
不值得被踩,因为你没有要求它。当你提供很少或没有信息时,请不要对帮助你的人进行负面评价。 - mwilson
以防万一,我也没有。 - Uber Bot

0

你可能想在创建新行时绑定每个新的DropDownList实例。然后,你可能想使用GridView.RowCreated事件。

void gvTemplateFields_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        (DropDownList)riskWorkDropDownList = (DropDownList)e.Row.FindControl("RiskWorkDropDownList");

        riskWorkDropDownList.DataSource = dataTable; //Your data table
        riskWorkDropDownList.DataBind(); 
    }
}

0

我假设您正在使用SqlExpress服务器,并尝试从数据库表中获取数据到下拉列表中,请尝试以下方法。

var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = "Server=.\\SqlExpress;Database=YourDatabasename;Trusted_Connection=True";
Cn.Open();
var Cm = Cn.CreateCommand();
Cm.CommandText = string.Format(@"Select * From DataTablename");
var Dr = Cm.ExecuteReader();

//add all data from database to dropdownlist
while (Dr.Read())
    {
       RiskWorkDropDownList.Items.Add(new ListItem(Dr.GetValue(1/*your table column*/).ToString()));
    }

Cn.Close();

0

只需将下拉列表的数据源设置为数据表即可完成此操作:

theDropDownList.DataSource = dataTable; //Your data table
theDropDownList.DataBind(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接