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();
}
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();
}
How do I bind a product name, then get a product id and price in the label result? The three attributes are from the same table in DB.
Code:
public partial class CreateOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "productName";
ddlProduct.DataValueField = "IDANDPRICE";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT productName, productID,productPrice,(productID + '-' + productPrice) AS IDANDPRICE from Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.ToString() ;
}
I find the following errors:
1- cast number filed to nvarchar in sql query
2- set AutoPostBack property of listbox to true
3- use ddlProduct.SelectedItem.Value for label2
I create a page and use your code and apply above suggestion, the following code work perfectly.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "name";
ddlProduct.DataValueField = "IdAndName";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT Id,Name,CAST( id as nvarchar(10) )+'-'+Name as IdAndName FROM Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.Value;
}
}
I have created a dropdownlist, which loads its data from a table column. Now I want to select the value of dropdownlist on Index_change_event.
protected void Page_Load(object sender, EventArgs e)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
//arr = Session["arr"].ToString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
}
Remove if (!IsPostBack) from DropDownList1_SelectedIndexChanged event and if (!IsPostBack) should be on Page_Load event.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
}
}
You are only checking !IsPostBack. As the event is firing from a postback this will never be run. Also, be careful that you are not re-binding the datasource and therefore changing the selected value on page_load.
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