I am trying to set data from database when user click on edit button but I have two cascading drop down list "Category" and "Subcategroy" but only Category is filled in dropdown list subcategory is throwing error.::::
System.NullReferenceException: Object reference not set to an instance of an object. at Jobopedia.SP_edit_new.btnEdit_Click(Object sender, EventArgs e) in C:\Users\Student\Documents\Jobopedia\Jobopedia\SP_edit_new.aspx.cs:line 200
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container" style="margin-left: 35%; width: 2000px">
<div class="row">
<div class="col-sm-4">
<div class="shadow-lg p-3 mb-5 bg-white rounded panel panel-blue">
<div class="panel-heading">
<center><p style="font-size: large; font-weight: bolder">Edit Business Details</p></center>
</div>
<div class="panel-body">
<center><asp:Label ID="lblMessage" runat="server" EnableViewState="false" ForeColor="Blue" style="font-size: large; font-weight: bolder"></asp:Label></center></br>
<p style="font-size: x-large; font-weight: bolder">Category</p>
<asp:DropDownList ID="cat" runat="server" class="form-control input-lg" Style="width: 100%; margin-bottom: 10px;" OnSelectedIndexChanged="cat_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
<p style="font-size: x-large; font-weight: bolder">Primary Profession</p>
<asp:DropDownList ID="DropDownList1" runat="server" class="form-control input-lg" Style="width: 100%; margin-bottom: 10px;" AutoPostBack="true" AppendDataBoundItems="false" >
</asp:DropDownList></br>
<p style="font-size: large; font-weight: bolder">City:</p>
<asp:DropDownList ID="DropDownList2" runat="server"
SelectedValue='<%# Bind("city") %>' class="form-control input-lg">
<asp:ListItem>--Select City--</asp:ListItem>
<asp:ListItem>Anand</asp:ListItem>
<asp:ListItem>Surat</asp:ListItem>
<asp:ListItem>Ahmedabad</asp:ListItem>
<asp:ListItem>Gandhinagar</asp:ListItem>
<asp:ListItem>Rajkot</asp:ListItem>
<asp:ListItem>Jamnagar</asp:ListItem>
</asp:DropDownList></br>
<p style="font-size: large; font-weight: bolder">Name :</p>
<asp:TextBox ID="txt_name" runat="server"></asp:TextBox></br>
<p style="font-size: large; font-weight: bolder">Address :</p>
<asp:TextBox ID="txt_Address" runat="server"></asp:TextBox></br>
<p style="font-size: large; font-weight: bolder">Toll Free No. :</p>
<asp:TextBox ID="txt_toll" runat="server"></asp:TextBox></br>
<p style="font-size: large; font-weight: bolder">Website Link :</p>
<asp:TextBox ID="txt_link" runat="server"></asp:TextBox></br>
<p style="font-size: large; font-weight: bolder">Payment Mode :</p>
<asp:CheckBox ID="Cashpay" Text="Cash" runat="server" CssClass="bg-info" />
<asp:CheckBox ID="Cardpay" Text="Card" runat="server" CssClass="bg-info" /></br>
</br><p style="font-size: large; font-weight: bolder">Email:</p>
<asp:TextBox ID="txt_email" runat="server" ReadOnly="true"></asp:TextBox></br>
<p style="font-size: large; font-weight: bolder">Image Name :</p>
<asp:TextBox ID="txt_img" runat="server" ReadOnly="true" ></asp:TextBox></br>
<p style="font-size: large; font-weight: bolder">Hours of Open :</p>
<fieldset>
<p style="font-size: large; font-weight: bolder">From:</p>
<asp:DropDownList ID="ddlTimeFrom" runat="server" class="form-control input-lg"></asp:DropDownList>
<p style="font-size: large; font-weight: bolder">To:</p>
<asp:DropDownList ID="ddlTimeTo" runat="server" class="form-control input-lg"></asp:DropDownList>
</fieldset></br>
<p style="font-size: large; font-weight: bolder">Image :</p>
<asp:Image ID="Image1" runat="server" Height="80px" Width="100px" /></br>
<asp:FileUpload ID="FileUpload1" runat="server" /></br>
<center><asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" CssClass="btn btn-info" Visible="false" />
<asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click" CssClass="btn btn-warning" /></center>
</div>
</div>
</div>
</div>
</div>
<table style="margin-left:12%;margin-top:5%">
<tr>
<td>
<asp:GridView ID="gvDepartments" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager"
HeaderStyle-CssClass="header" EmptyDataText="No Records Found" RowStyle-CssClass="rows" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<asp:Label ID="lblcat" runat="server" Text='<%#Eval("Category") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Business Name">
<ItemTemplate>
<asp:Label ID="lblBname" runat="server" Text='<%#Eval("Bussiness_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Eval("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID="lblAddress" runat="server" Text='<%#Eval("address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Toll Free No.">
<ItemTemplate>
<asp:Label ID="lbltoll" runat="server" Text='<%#Eval("toll_free") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Website Link">
<ItemTemplate>
<asp:Label ID="lblweb" runat="server" Text='<%#Eval("website_link") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Payment Mode">
<ItemTemplate>
<asp:Label ID="lblpay" runat="server" Text='<%#Eval("payment_mode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%#Eval("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image Name">
<ItemTemplate>
<asp:Label ID="lblimg" runat="server" Text='<%#Eval("Image_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Hours of Open">
<ItemTemplate>
<asp:Label ID="lblopen" runat="server" Text='<%#Eval("h_open") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="img" runat="server" ImageUrl='<%# Eval("Images") %>' Height="80px" Width="100px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit" OnClick="btnEdit_Click" CssClass="btn btn-primary" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure? want to delete the record.');"
OnClick="btnDelete_Click" CssClass="btn btn-danger" />
<asp:Label ID="Id" runat="server" Text='<%#Eval("Id") %>' Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<input type="hidden" runat="server" id="Id" />
</div>
</asp:Content>
public partial class SP_edit_new : System.Web.UI.Page
{
SqlConnection mycon = new SqlConnection(ConfigurationManager.ConnectionStrings["Q_SS_regnConnectionString1"].ToString());
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
BindTime();
if (!this.IsPostBack)
{
string query = "select DISTINCT Category from Category_tbl";
BindDropDownList(cat, query, "Category", "Category");
//DropDownList1.Enabled = false;
//DropDownList1.Items.Insert(0, new ListItem("0"));
}
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value)
{
string conString = ConfigurationManager.ConnectionStrings["Q_SS_regnConnectionString1"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
con.Close();
}
}
}
private void BindTime()
{
// Set the start time (00:00 means 12:00 AM)
DateTime StartTime = DateTime.ParseExact("00:00", "HH:mm", null);
// Set the end time (23:55 means 11:55 PM)
DateTime EndTime = DateTime.ParseExact("23:55", "HH:mm", null);
//Set 5 minutes interval
TimeSpan Interval = new TimeSpan(0, 5, 0);
//To set 1 hour interval
//TimeSpan Interval = new TimeSpan(1, 0, 0);
ddlTimeFrom.Items.Clear();
ddlTimeTo.Items.Clear();
while (StartTime <= EndTime)
{
ddlTimeFrom.Items.Add(StartTime.ToShortTimeString());
ddlTimeTo.Items.Add(StartTime.ToShortTimeString());
StartTime = StartTime.Add(Interval);
}
ddlTimeFrom.Items.Insert(0, new ListItem("--Select--", "0"));
ddlTimeTo.Items.Insert(0, new ListItem("--Select--", "0"));
}
void FillGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Q_SS_regnConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("Select * from SP_Afterlogin2 where email='" + Session["mail"].ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gvDepartments.DataSource = dt;
gvDepartments.DataBind();
}
void ClearControls()
{
DropDownList1.ClearSelection();
DropDownList2.ClearSelection();
ddlTimeFrom.ClearSelection();
ddlTimeTo.ClearSelection();
txt_name.Text = "";
txt_toll.Text = "";
txt_link.Text = "";
txt_email.Text = "";
txt_img.Text = "";
Image1.ImageUrl = "";
txt_Address.Text = "";
Id.Value = "";
Cashpay.Checked = false;
Cardpay.Checked = false;
btnUpdate.Visible = true;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow grow = btn.NamingContainer as GridViewRow;
string path = "~/uploads/";
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
if (FileUpload1.HasFile)
{
path += FileUpload1.FileName;
FileUpload1.SaveAs(MapPath(path));
}
else
{
fileName = txt_img.Text;
path = Image1.ImageUrl;
}
UpdateFile(path, fileName);
ClearControls();
FillGrid();
lblMessage.Text = "Updated Successfully.";
}
private void UpdateFile(string path, string fileName)
{
string joinCashCard = "";
if (Cardpay.Checked)
{
joinCashCard += Cardpay.Text + ",";
}
if (Cashpay.Checked)
{
joinCashCard += Cashpay.Text + ",";
}
List<String> open = new List<String>();
if (ddlTimeFrom.SelectedIndex > 0 && ddlTimeTo.SelectedIndex > 0)
{
open.Add(ddlTimeFrom.Text);
open.Add(ddlTimeTo.Text);
}
string open2 = string.Join(",", open);
//List<string> mode = new List<string>();
//if (Cashpay.Checked) { mode.Add(Cashpay.Text); }
//if (Cardpay.Checked) { mode.Add(Cardpay.Text); }
//string payment = string.Join(", ", mode);
string constr = ConfigurationManager.ConnectionStrings["Q_SS_regnConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("UPDATE SP_Afterlogin2 SET Images =@Path,Bussiness_name=@Bussiness_name,city=@city,Image_name=@Image_name,name=@name,toll_free=@toll_free,website_link=@website_link,payment_mode=@payment_mode,email=@email,address=@address,h_open=@h_open,Category=@Category WHERE Id =@Id", con);
cmd.Parameters.AddWithValue("@Id", Id.Value);
cmd.Parameters.AddWithValue("@Path", path);
cmd.Parameters.AddWithValue("@Bussiness_name", DropDownList1.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@city", DropDownList2.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@name", txt_name.Text);
cmd.Parameters.AddWithValue("@toll_free", txt_toll.Text);
cmd.Parameters.AddWithValue("@website_link", txt_link.Text);
cmd.Parameters.AddWithValue("@payment_mode", joinCashCard.TrimEnd(','));
cmd.Parameters.AddWithValue("@email", txt_email.Text);
cmd.Parameters.AddWithValue("@Image_name",fileName);
cmd.Parameters.AddWithValue("@address", txt_Address.Text);
cmd.Parameters.AddWithValue("@h_open", open2);
cmd.Parameters.AddWithValue("@Category", cat.SelectedValue.ToString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
protected void btnClear_Click(object sender, EventArgs e)
{
ClearControls();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
Button btn = sender as Button;
GridViewRow grow = btn.NamingContainer as GridViewRow;
Id.Value = (grow.FindControl("Id") as Label).Text;
Image img = (grow.FindControl("img") as Image);
txt_email.Text = (grow.FindControl("lblemail") as Label).Text;
txt_link.Text = (grow.FindControl("lblweb") as Label).Text;
txt_img.Text = (grow.FindControl("lblimg") as Label).Text;
txt_name.Text = (grow.FindControl("lblname") as Label).Text;
txt_toll.Text = (grow.FindControl("lbltoll") as Label).Text;
txt_Address.Text = (grow.FindControl("lblAddress") as Label).Text;
Image1.ImageUrl = img.ImageUrl;
btnUpdate.Visible = true;
string value3 = (grow.FindControl("lblcat") as Label).Text;
cat.ClearSelection();
cat.Items.FindByValue(value3).Selected = true;
string value = (grow.FindControl("lblBname") as Label).Text;
DropDownList1.ClearSelection();
DropDownList1.Items.FindByValue(value).Selected = true;
string value2 = (grow.FindControl("lblcity") as Label).Text;
DropDownList2.ClearSelection();
DropDownList2.Items.FindByValue(value2).Selected = true;
string from = (grow.FindControl("lblopen") as Label).Text;
string[] parts = from.Split(',');
ddlTimeFrom.ClearSelection();ddlTimeTo.ClearSelection();
ddlTimeFrom.Items.FindByValue(parts[0].Trim()).Selected = true;
ddlTimeTo.Items.FindByValue(parts[1].Trim()).Selected = true;
string pay = (grow.FindControl("lblpay") as Label).Text;
if (pay == "Cash")
{
Cashpay.Checked = true;
Cardpay.Checked = false;
}
if (pay == "Card,Cash")
{
Cashpay.Checked = true;
Cardpay.Checked = true;
}
if (pay == "Cash,Card")
{
Cashpay.Checked = true;
Cardpay.Checked = true;
}
if (pay == "Card")
{
Cardpay.Checked = true;
Cashpay.Checked = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
ClearControls();
Button btn = sender as Button;
GridViewRow grow = btn.NamingContainer as GridViewRow;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete FROM SP_Afterlogin2 where Id=@Id";
cmd.Parameters.AddWithValue("@Id", (grow.FindControl("Id") as Label).Text);
cmd.Connection = mycon;
mycon.Open();
cmd.ExecuteNonQuery();
mycon.Close();
FillGrid();
string filename = (grow.FindControl("lblimg") as Label).Text;
ImageDeleteFromFolder(filename);
lblMessage.Text = "Deleted Successfully.";
}
catch(Exception ex)
{
Response.Write(ex);
}
finally
{
if (mycon.State == ConnectionState.Open)
mycon.Close();
}
}
private void ImageDeleteFromFolder(string name)
{
string file_name = name;
string path = Server.MapPath(@"~/uploads/" + name);
//string filePath = path + file_name;
FileInfo filein = new FileInfo(path);
if (filein.Exists) //check file exsit or not
{
filein.Delete();
}
else
{
lblMessage.Text = " This file does not exists";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}
protected void cat_SelectedIndexChanged(object sender, EventArgs e)
{
string category = cat.SelectedItem.Value;
string query = string.Format("select DISTINCT Sub_category from Category_tbl where Category='{0}' and Sub_category!=' '", category);
BindDropDownList(DropDownList1, query, "Sub_category", "Sub_category");
}
}