您好我是C#的新手,我的技能非常不足,我希望将SQL表中的数据导入我的'asp:DropDownList'在一张桌子里。
我收到此错误: System.NullReferenceException:对象引用未设置为对象的实例 。
前端html看起来像这样:
<asp:Table ID="Table1" runat="server" Font-Size="Medium" Width="960" BorderWidth="3" CellPadding="5" CellSpacing="5" CssClass="table table-bordered table-striped table-hover table-condensed table-responsive">
<asp:TableHeaderRow runat="server" Font-Bold="true">
<asp:TableHeaderCell Width="20%">Activity</asp:TableHeaderCell>
<asp:TableHeaderCell>Hazards</asp:TableHeaderCell>
<asp:TableHeaderCell Width="15%">Risk Level</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow ID="TableRow1" runat="server" >
<asp:TableCell>Camping</asp:TableCell>
<asp:TableCell>Emergency evacuation</asp:TableCell>
<asp:TableCell><asp:DropDownList ID="ddl1" runat="server"></asp:DropDownList></asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
我简要介绍的C#代码是:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty((string)Session["TripCode"]))
{
txtTripCode.Text = (string)Session["TripCode"];
}
else
{
txtTripCode.Text = "NOT PROVIDED";
}
if (!string.IsNullOrEmpty((string)Session["TripOrg"]))
{
txtTripOrg.Text = (string)Session["TripOrg"];
}
else
{
txtTripOrg.Text = "ERROR: NO DATA PROVIDED";
}
if (!string.IsNullOrEmpty((string)Session["TripDesc"]))
{
txtTripDesc.Text = (string)Session["TripDesc"];
}
else
{
txtTripDesc.Text = "ERROR: NO DATA PROVIDED";
}
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 1000 [MainActivityID],[ID],[Activity],[Hazards],[Risk_Level],[Controls] FROM [STRIDES_SQL].[dbo].[STRIDES_RA_Activities]"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ddl1.DataSource = cmd.ExecuteReader();
ddl1.DataTextField = "Name";
ddl1.DataValueField = "MainActivityID";
ddl1.DataBind();
con.Close();
}
}
ddl1.Items.Insert(0, new ListItem("--Select Customer--", "0"));
}
}
有没有办法可以阻止这种情况发生?
我很感激任何帮助或理解,请提前感谢任何人提出这个问题!
答案 0 :(得分:0)
检查你的web.config以查看配置中的constr - &gt; ConnectionStrings部分。如果不存在,请添加连接字符串。
检查 https://www.connectionstrings.com/正确的语法。
另外,行
ddl1.DataTextField = "Name";
会给你下一个错误。名称字段不是您的查询的一部分。