Hi I am quite new to C# and my skills are very inadequate, I am looking to bring data from a SQL Table into my 'asp:DropDownList' within a table.
I am getting this error: System.NullReferenceException: Object reference not set to an instance of an object.
The front end html looks like this:
<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>
The C# code I have briefly gone through is this:
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"));
}
}
Is there a way in which i can stop this happening?
I am grateful to any help or understanding, thank you in advance to anyone picking this up!