When I fill the registration form and click on the button to move to user panel it does not move to the user panel, it freezes on the registration. In the user panel code behind it shows this message:
Object reference not set to an instance of an object.
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email,Country, State,City, Post, Img, Logo,RegDate) VALUES (#UID,#FN,#LN,#Password,#RePass,#Email,#Country,#State,#City,#Post,#Img,#Logo,#RegDate)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#UID", UsrNme.Text);
cmd.Parameters.AddWithValue("#FN", fnbox.Text);
cmd.Parameters.AddWithValue("#LN", lnamebox.Text);
cmd.Parameters.AddWithValue("#Password", passtxtbx1.Text);
cmd.Parameters.AddWithValue("#RePass", passtxtbx2.Text);
cmd.Parameters.AddWithValue("#Email", emailbox.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Post", postbox.Text);
cmd.Parameters.AddWithValue("#Img", persimgFileUpload1.FileName);
cmd.Parameters.AddWithValue("#Logo", logoFileUpload.FileName);
//Get the Current Date Time here
cmd.Parameters.AddWithValue("#RegDate", DateTime.Now);
if (!string.IsNullOrEmpty(UsrNme.Text))
{
Lblcheckusername.Text = "User Name Already Exist";
Lblcheckusername.ForeColor = System.Drawing.Color.Red;
}
else
{
Lblcheckusername.Text = "User Name Available";
Lblcheckusername.ForeColor = System.Drawing.Color.Green;
}
if (persimgFileUpload1.HasFile)
{
persimgFileUpload1.SaveAs(Server.MapPath("~/images/users/" + persimgFileUpload1.FileName));
}
if (logoFileUpload.HasFile)
{
logoFileUpload.SaveAs(Server.MapPath("~/images/Logos/" + logoFileUpload.FileName));
}
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
Here is the user panel codebehind where the error appears on the first code line:
USRNMElbl.Text = Session["UsrNme"].ToString();
if (Session["UsrNme"] != null)
{
}
if (!Page.IsPostBack)
{
DataTable countrycascd = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [countryID],[country] FROM [countr]", con);
adaptar.Fill(countrycascd);
countrdrdolst.DataSource = countrycascd;
countrdrdolst.DataTextField = "country";
countrdrdolst.DataValueField = "countryID";
countrdrdolst.DataBind();
}
countrdrdolst.Items.Insert(0, new ListItem("Välj land", "0"));
}
if (!Page.IsPostBack)
{
DataTable Sectiondt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [CateID],[Category] FROM [Section]", con);
adaptar.Fill(Sectiondt);
Catedrdoads.DataSource = Sectiondt;
Catedrdoads.DataTextField = "Category";
Catedrdoads.DataValueField = "CateID";
Catedrdoads.DataBind();
}
Catedrdoads.Items.Insert(0, new ListItem("Select Section", "0"));
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 1;
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 2;
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 3;
}
protected void addadsbtn_Click(object sender, EventArgs e)
{
Guid newGUID = Guid.NewGuid();
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO [ads] ([Section], [Category], [UID], [AdsTit], [AdsDesc], [Country], [State], [City], [AdsPrice], [Img1], [img2], [img3], [img4], [img5], [Wtags]) VALUES (#Section, #Category, #UID, #AdsTit, #AdsDesc, #Country, #State, #City, #AdsPrice, #Img1, #img2, #img3, #img4, #img5, #Wtags)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#Section", Catedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Category", SubCatedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#UID", USRNMElbl.Text);
cmd.Parameters.AddWithValue("#AdsTit", addadstittxtbx.Text);
//cmd.Parameters.AddWithValue("#AdsDesc", Editor1.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AdsPrice", adsaddpristxtbx.Text);
cmd.Parameters.AddWithValue("#Img1", FileUpload1.FileName);
cmd.Parameters.AddWithValue("#Img2", FileUploadImg2.FileName);
cmd.Parameters.AddWithValue("#Img3", FileUploadImg3.FileName);
cmd.Parameters.AddWithValue("#Img4", FileUploadImg4.FileName);
cmd.Parameters.AddWithValue("#Img5", FileUploadImg5.FileName);
cmd.Parameters.AddWithValue("#Wtags", addadswtagtxtbtn.Text);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
The problem might be your Session["UsrNme"] is null
if (Session["UsrNme"] != null)
{
USRNMElbl.Text = Session["UsrNme"].ToString();
}
else
{
return;
}
You could also read http://www.codingdefined.com/2014/06/object-reference-not-set.html
Related
I would like to know how can I display fixed data, based on the cascading dropdown list the user chooses? For example, I have 3 dropdown lists, on the last dropdown list if the user chooses "Yes", textbox will display "Position is approved" and if the user chooses "No", textbox will display "Position not approved". This is my code. I don't know what else to, please help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillPackage();
}
}
private void FillPackage()
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT TopID, ToPackage FROM TableTop1";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl1.DataSource = objDs.Tables[0];
ddl1.DataTextField = "ToPackage";
ddl1.DataValueField = "TopID";
ddl1.DataBind();
ddl1.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "No Package found";
}
}
private void FillPurpose(int TopID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PurposeID, Purpose FROM TablePurpose1 WHERE TopID =#TopID";
cmd.Parameters.AddWithValue("#TopID", TopID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl2.DataSource = objDs.Tables[0];
ddl2.DataTextField = "Purpose";
ddl2.DataValueField = "PurposeID";
ddl2.DataBind();
ddl2.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
private void FillReason(int PurposeID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ReasonID, Reason FROM TableReason1 WHERE PurposeID =#PurposeID";
cmd.Parameters.AddWithValue("#PurposeID", PurposeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl3.DataSource = objDs.Tables[0];
ddl3.DataTextField = "Reason";
ddl3.DataValueField = "ReasonID";
ddl3.DataBind();
ddl3.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
Since you have a Page_Load method in your snippet I'll consider your are using asp.net web forms. If that is the case you just have to handle the event emitted by the DropDownList component when it is changed.
I'm your c# code you should create a method to handle the event of an item being selected in your DropDownList, something like this:
protected void ItemSelected(object sender, EventArgs e)
{
if (ddl3.SelectedItem.Value == "Yes")
{
// Change text box text
}
}
And then you just have to hook your event handler to the component:
<asp:DropDownList ID="ddl3" runat="server" AutoPostBack="True"
onselectedindexchanged="ItemSelected">
</asp:DropDownList>
This is neither producing an error nor output. Help me out in this. Here my code is :
public partial class ScoHelpDesk : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
SqlDataAdapter adapt;
DataTable dt;
SqlConnection con2, con3;
SqlCommand cmd, cmd1, cmd2;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData_Sheet();
}
}
protected void InsertData1(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlserver"].ConnectionString);
TextBox t1 = (TextBox)GridView1.FooterRow.FindControl("TextBox2");
TextBox t2 = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
TextBox t3 = (TextBox)GridView1.FooterRow.FindControl("TextBox6");
TextBox t4 = (TextBox)GridView1.FooterRow.FindControl("TextBox8");
TextBox t5 = (TextBox)GridView1.FooterRow.FindControl("TextBox10");
TextBox t6 = (TextBox)GridView1.FooterRow.FindControl("TextBox12");
cmd = new SqlCommand("insert into tblHelpDesk (Name,Purpose,ContactNo,AlternativeNo,Email,Address) values(#Name,#Purpose,#ContactNo,#AlternativeNo,#Email,#Address)", con);
con.Open();
cmd.Parameters.AddWithValue("#Name", t1.Text);
cmd.Parameters.AddWithValue("#Purpose", t2.Text);
cmd.Parameters.AddWithValue("#ContactNo", t3.Text);
cmd.Parameters.AddWithValue("#AlternativeNo", t4.Text);
cmd.Parameters.AddWithValue("#Email", t5.Text);
cmd.Parameters.AddWithValue("#Address", t6.Text);
cmd.ExecuteNonQuery();
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
catch (Exception ex)
{ }
}
private void BindData_Sheet()
{
DataTable dt = new DataTable();
using (SqlConnection con2 = new SqlConnection(con.ConnectionString))
{
string strQuery = "SELECT * FROM tblHelpDesk ";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
I have created 2 DropDownLists First dropdown contains "TeamName" and second one contain "TeamMember" name. The requirement is when we select particular TeamName from dropdown second dropdown should automatic populates the team member name and after button click data should be inserted in database,It works fine for first button click but second time on the same page "TeamName" dropdown does not show name of department,suddenly it gets lost.So Please suggest me what I need to do to resolve this issue??
Following is the code which I did to achieve this task
User.aspx page code:
User.aspx.cs page code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTeamName();
txtCurrentDate.Text = DateTime.Now.ToString("MM-dd-yyyy");
txtCurrentDate.ForeColor = System.Drawing.Color.Green;
}
}
private void BindTeamName()
{
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamName", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl1.DataSource = ds;
ddl1.DataTextField = "TeamName";
ddl1.DataValueField = "TeamId";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
int TeamId = Convert.ToInt32(ddl1.SelectedValue);
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamResource where TeamId=" + TeamId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl2.DataSource = ds;
ddl2.DataTextField = "EmpName";
ddl2.DataValueField = "EmpId";
ddl2.DataBind();
ddl2.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(SqlString))
{
SqlCommand cmd = new SqlCommand("InsertUserData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#WorkDate", txtCurrentDate.Text);
cmd.Parameters.AddWithValue("#TeamName", ddl1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#TeamMember", ddl2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AvailableBandwidth", ddlAvailable.SelectedItem.Value);
con.Open();
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
}
}
I would re-bind the "TeamName" dropdown list after a successful save.
//btnSubmit_Click
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
BindTeamName(); //re-bind the initial dropdown so you can select a new team
}
Actually you can use that method either way, depending on what ClearFields() does.
I have this error "The name 'GetData' does not exist in the current context". I had tried to declare the getdata() function but it still got error.
public partial class v2_kradescription : System.Web.UI.Page
{
private String conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
my c# code behind already has
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindData();
}
}
here, I'm using getdata()
protected void BindData()
{
string conn = "select kr_id,kr_position,kr_description from tblKRAObjective";
SqlCommand cmd = new SqlCommand(conn);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void AddNewJob(object sender, EventArgs e)
{
if (e.Equals("btnAdd"))
{
string jid = ((TextBox)GridView1.FooterRow.FindControl("txtid")).Text;
string jposition = ((TextBox)GridView1.FooterRow.FindControl("txtposition")).Text;
string jdescription = ((TextBox)GridView1.FooterRow.FindControl("txtdescription")).Text;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into tblJobDescription (j_id, j_position, j_description) " + "values(#j_id, #j_position, #j_description);" + "select j_id,j_position,j_description from tblJobDescription";
cmd.Parameters.Add("#j_id", SqlDbType.VarChar).Value = jid;
cmd.Parameters.Add("#j_position", SqlDbType.VarChar).Value = jposition;
cmd.Parameters.Add("#j_description", SqlDbType.VarChar).Value = jdescription;
GridView1.DataSourceID = GetData(con);
GridView1.DataBind();
}
}
protected void EditDescription(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateDescription(object sender, GridViewUpdateEventArgs e)
{
string jid = ((TextBox)GridView1.FooterRow.FindControl("txtkr_id")).Text;
string jposition = ((TextBox)GridView1.FooterRow.FindControl("txtkr_position")).Text;
string jdescription = ((TextBox)GridView1.FooterRow.FindControl("txtkr_description")).Text;
SqlCommand con = new SqlCommand(conn);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update tblJobDescription set j_id=#j_id,j_position=#j_position where j_id=#j_id ";
cmd.Parameters.Add("#j_id", SqlDbType.Int).Value = jid;
cmd.Parameters.Add("#j_position", SqlDbType.Int).Value = jposition;
cmd.Parameters.Add("#j_description", SqlDbType.Int).Value = jdescription;
GridView1.EditIndex = -1;
GridView1.DataSourceID = GetData(cmd);
GridView1.DataBind();
}
protected void DeleteDescription(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " delete from tblJobDescription where j_id=#j_id";
cmd.Parameters.Add("#j_id", SqlDbType.VarChar).Value = lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
BindData();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void btnPreview_Click(object sender, EventArgs e)
{
Response.Redirect("kra_pdf.aspx");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string jicno = (string)(Session["s_icno"]);
string jobid = "";
string jobdescription = "";
string jobposition = "";
try
{
string query = "InsertJobDescription";
// get requester name, companyid, primary appraiser of requester
String queryA = "SELECT kr_id, kr_description, kr_position FROM tblKRAObjective WHERE s_icno = '" + jicno + "' ";
SqlCommand cmdA = new SqlCommand(conn);
SqlDataReader drA = cmdA.ExecuteReader();
if (drA.Read())
{
jobid = drA["j_id"].ToString();
jicno = drA["j_icno"].ToString();
jobdescription = drA["j_descpription"].ToString();
jobposition = drA["j_position"].ToString();
}
drA.Close();
SqlCommand cmd1 = new SqlCommand(conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#j_icno", SqlDbType.NVarChar).Value = jicno.ToString();
cmd1.Parameters.Add("#j_description", SqlDbType.NVarChar).Value = jobdescription.ToString();
cmd1.Parameters.Add("#j_position", SqlDbType.NVarChar).Value = jobposition.ToString();
cmd1.ExecuteNonQuery();
}
catch (Exception ex)
{
lblMsg.Text = ex.Message; //" Error while saving the record.";
}
Response.Redirect("kra_dashboard.aspx");
}
}
but anyway, I'm getting the error
The name 'GetData' does not exist in the current context
so, where is my mistake ?
I want to fill datagridview when rows affected=< 0 but i get error in line 47 gridview (id) = "correctgridview" runat = "server"
the first case work well but the error in the datagridview
mycode
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void insertButton_Click(object sender, EventArgs e)
{
int rowsaffected = 0;
dataset ds = new dataset();
SqlConnection cn = new SqlConnection(#"Server=.\SQLEXPRESS; DataBase=attend; Integrated Security=true;");
SqlCommand cmd;
cn.Open();
cmd = new SqlCommand("atten", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param.ParameterName = "#myid";
param.Value = idTextBox.Text;
cmd.Parameters.Add(param);
rowsaffected = cmd.ExecuteNonQuery();
if (rowsaffected > 0)
{
resultLabel.Text = "added successful";
}
else
{
resultLabel.Text = "attend error";
SqlCommand command;
command = new SqlCommand("select id, courses.course , course_date , st_lec , location from courses inner join regestration on courses.course = regestration.course where id = 2", cn);
SqlDataAdapter adapte = new SqlDataAdapter(command);
DataTable Dt = new DataTable();
adapte.Fill(Dt);
correctGridView.DataSource = Dt;
correctGridView.DataBind();
}
cn.Close();
}
}