How to use Entity Framework to upload data? - c#

I have this web written in C# , that provides a table for user with these data ( ID , FROM , TITLE , MESSAGE ) Table name on database is MessagesTable
My question is how can I use Entity Framework to upload data on the table , I used to do it using ConnectionStrings.
public partial class UsersEF : System.Web.UI.Page
{
static string ConnStr = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
int SelectedID = 0;
SqlConnection con;
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//GridViewRow grdrw = GridView1.Rows[e.RowIndex];
//SelectedID = int.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
SelectedID = int.Parse(e.NewValues["Id"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE MessagesTable set [From]=#From ,[To] =#To ,Title =#Title ,Message = #Message WHERE Id = #Id";
cmd.Parameters.Add(new SqlParameter("#id",SqlDbType.Int)).Value=SelectedID;
cmd.Parameters.Add(new SqlParameter("#From",SqlDbType.NVarChar ,50)).Value = e.NewValues["From"].ToString();
cmd.Parameters.Add(new SqlParameter("#To", SqlDbType.NVarChar, 50)).Value= e.NewValues["To"].ToString();
cmd.Parameters.Add(new SqlParameter("#Title", SqlDbType.NVarChar, 50)).Value = e.NewValues["Title"].ToString();
cmd.Parameters.Add(new SqlParameter("#Message", SqlDbType.NVarChar, 150)).Value = e.NewValues["Message"].ToString();
if (cmd.ExecuteNonQuery() > 0)
{
e.Cancel = true;
GridView1.EditIndex = -1;
BindGrid();
}
else {
e.Cancel = false;
};
}
protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
// SelectedID = int.Parse(GridView1.Rows[e.NewEditIndex].Cells[0].Text);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedID =int.Parse (GridView1.SelectedRow.Cells[0].Text);
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
SelectedID = int.Parse(GridView1.Rows[e.NewEditIndex].Cells[0].Text);
BindGrid();
//SelectedID = int.Parse();
}
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConnStr);
con.Open();
if (!Page.IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
var context = new TestDBEntities();
//DataTable table = new DataTable();
var table = context.MessagesTable.ToList();
/*
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Id,[From],[To],Title,Message from MessagesTable ";
//DataSet dataSet = new DataSet();
DataTable table=new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
*/
GridView1.DataSource = table;//dataSet.Tables[0];
GridView1.DataBind();
}
}

You can update it this way using EF -
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SelectedID = int.Parse(e.NewValues["Id"].ToString());
// retrieve from db
var messages = this.context.MessagesTable.FirstOrDefault(x=>x.id == SelectedID);
// update values
messages.From = int.Parse(e.NewValues["From"].ToString());
messages.To= int.Parse(e.NewValues["To"].ToString());
messages.Title = int.Parse(e.NewValues["Title"].ToString());
messages.Message= int.Parse(e.NewValues["Message"].ToString());
//Save changes into db
this.context.MessagesTable.Update(messages);
this.context.SaveChanges();
}

Related

how to fix my code when it says Exception Unhandled?

So I have written my code but every time i try to execute it it says "exception unhandled System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'" and it always shows it at the line that says da.Fill(dt);
please tell me how to fix it
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The best practice for handling connection objects is to store them in a local variable and dispose them as soon as possible. You don't need to worry overhead opening and closing connections; they are actually managed in a pool and it's very efficient.
You are storing your connection at the class level and not handling the connection properly. If you store it at the class level, it could time out between button clicks, and it's taking up resources the whole time. Close or dipose the connection right away, which will return it to the connection pool.
To fix, follow this sort of pattern:
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
//Get rid of member variable for the connection. Add constant for connection string.
private const string ConnectionString = #"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True";
private void button1_Click(object sender, EventArgs e)
{
//Use using and use a local variable for the connection
using (var con=new SqlConnection(this.ConnectionString))
{
con.Open();
var cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
//Create a new connection each time you need one
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
else if (comboBox1.Text == "EmployeeName")
{
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
your connection property is not intialised.Click button_click to have your connection intialised.or inside Textbox5_textchanged check for connection con.Isopen else intialize connection object again.
I think you shoul initialize connection object first of all.
You can change your code with the below code and pls return result:
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(con == null)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
}
if(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter da = null;
DataTable dt = new DataTable();
if(comboBox1.Text == "EmployeeID")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else if (comboBox1.Text == "EmployeeName")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else
{
}
dataGridView1.DataSource = dt;
}
Your connection has not been initialized at the time you're textBox5 text has changed. Move it to your constructor.
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Unable to update record in textbox in C#

I am trying to do edit inside grid view. When I click edit button to update record in text box it shows previous record. Please check. I think the error is in Row updating event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill_grd1();
}
}
public void fill_grd1()
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grd1.DataSource = ds;
grd1.DataBind();
}
else
{
grd1.DataSource = null;
grd1.DataBind();
}
con.Close();
}
protected void savebtn_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cname", txtcname.Text);
cmd.ExecuteNonQuery();
con.Close();
fill_grd1();
}
protected void grd1_RowEditing(object sender, GridViewEditEventArgs e)
{
grd1.EditIndex = e.NewEditIndex;
fill_grd1();
}
protected void grd1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(grd1.DataKeys[e.RowIndex].Value.ToString());
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_delete", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cid", id);
cmd.ExecuteNonQuery();
con.Close();
fill_grd1();
}
protected void grd1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox TB1 = (TextBox)grd1.Rows[e.RowIndex].FindControl("edittxtcname");
int id = int.Parse(grd1.DataKeys[e.RowIndex].Value.ToString());
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cid", id);
cmd.Parameters.AddWithValue("#cname", TB1.Text);
cmd.ExecuteNonQuery();
con.Close();
grd1.EditIndex = -1;
fill_grd1();
}
protected void grd1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grd1.EditIndex = -1;
fill_grd1();
}
protected void grd1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void grd1_RowCommand(object sender, GridViewCommandEventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_status_change", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cid", e.CommandArgument);
cmd.ExecuteNonQuery();
con.Close();
fill_grd1();
}

The name 'GetData(cmd)' does not exist in the current context

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 ?

How can update Datagridview content when DataTable changed

I want the DataGridView gets updated when DataTable changes (myAdapter.DeleteCommand = cmd;).
Please help me. Thanks
My code is:
1.
public void DoCommand(String commandText, ActionType actionType, SqlParameter[] sqlParameter)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = getConnection();
cmd.CommandText = commandText;
cmd.Parameters.AddRange(sqlParameter);
if (actionType == ActionType.Insert)
myAdapter.InsertCommand = cmd;
else if (actionType == ActionType.Update)
myAdapter.UpdateCommand = cmd;
else if (actionType == ActionType.Delete)
myAdapter.DeleteCommand = cmd;
cmd.ExecuteNonQuery();
}
}
2.
DataTable dt;
private void frmCustomers_Load(object sender, EventArgs e)
{
dt = obj.SelectCustomer();
dgCustomer.DataSource = localDt;
}
3.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
obj.DoCommand("delete from tbl_customer where customer_id = 1", ActionType.Delete);
}

facing an error with registration btn

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

Categories

Resources