image update with other related records in sql database - c#

I have a table called Phase it contains other columns and also an image column. All is working fine except that when i want to update the image it says " i cannot implicitly convert nvarchar to varbinary(max) and also when i want to update any one of the columns apart from the image it shows me the same error. Please help me out what am i doing wrong? Below is my aspx and aspx.cs codes respectively:
protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = e.RowIndex;
GridViewRow row = (GridViewRow)gv1.Rows[index];
Label eid = (Label)row.FindControl("lbleid");
TextBox date = (TextBox)row.FindControl("txtdate");
DropDownList ddl1 = (DropDownList)row.FindControl("ProjectID");
DropDownList ddl2 = (DropDownList)row.FindControl("ProjectTypeID");
DropDownList ddl3 = (DropDownList)row.FindControl("StateID");
DropDownList ddl4 = (DropDownList)row.FindControl("LGAID");
DropDownList ddl5 = (DropDownList)row.FindControl("CommunityID");
DropDownList ddl6 = (DropDownList)row.FindControl("CoyID");
FileUpload fu = (FileUpload)row.FindControl("fu1");
foreach (HttpPostedFile postedFile in fu.PostedFiles)
{
string filename = Path.GetFileName(postedFile.FileName);
string contentType = postedFile.ContentType;
using (Stream fs = postedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
SqlCommand cmd = new SqlCommand("update Phase set Photo = '" + fu.FileName + "' where Phase_1ID=" + Convert.ToInt32(eid.Text) + "", con);
con.Open();
int res = cmd.ExecuteNonQuery();
con.Close();
}
SqlCommand cmd1 = new SqlCommand("update Phase set DateOfVisit='" + date.Text + "', ProjectTitle='" + ddl1.Text + "', Type='" + ddl2.Text + "', StateName='" + ddl3.Text + "', LGName='" + ddl4.Text + "', CommunityName='" + ddl5.Text + "', CompanyName='" + ddl6.Text + "", con);
con.Open();
int res1 = cmd1.ExecuteNonQuery();
con.Close();
if (res1 == 1)
{
Response.Write("<script>alert('Updation done!')</script>");
}
gv1.EditIndex = -1;
gv1.DataBind();
}
}
}
}

Related

Reading access database

I have written code to return values based on a search box however at times, the value entered into the search box can apply to several records within an MSAccess DB.
Is there a way where I can scroll through the records that apply to the value in the search box by using a button?
public void LoopThroughRecs(OleDbDataReader Data)
{
Data.Read();
{
FirstName.Text = Data["Initial"].ToString();
LastName.Text = Data["Surname"].ToString();
Address1.Text = Data["Address 1"].ToString();
Address2.Text = Data["Address 2"].ToString();
Address3.Text = Data["Address 3"].ToString();
TownCity.Text = Data["Post Town"].ToString();
PostCode.Text = Data["Post Code"].ToString();
Telephone.Text = Data["Telephone"].ToString();
LstSvcDat.Text = Data["LastService"].ToString();
BoilerMan.Text = Data["Manufacturer"].ToString();
BoilerMod.Text = Data["Model"].ToString();
}
Data.Close();
}
public void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT CustCode,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone,Equipment.CustID AS CustID,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model,Equipment.LastService AS LastService FROM Contacts LEFT OUTER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Archived = 0 AND (CustCode = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR Surname = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR [Post Town] = '" + textBox12.Text + "' OR [Post Code] = '" + textBox12 + "')", conn);
OleDbDataReader Data = command.ExecuteReader();
LoopThroughRecs(Data);
}
finally
{
conn.Close();
}
}

Textbox value does not get updated in asp.net

I have some Textboxes in my page. I am getting values from Database in and updating Textboxes in my page load. I have a code to update values in database behind update button. the problem is that when I change the textbox value and click update button, the value in textbox is again the original one. It retains its value. My code is
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"].ToString());
if (FileUpload1.HasFile)
{
HttpPostedFile Image = FileUpload1.PostedFile;
string contentType = Image.ContentType;
if (contentType.Equals("application/octet-stream"))
{
contentType = "application/pdf";
}
else if (contentType.Equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
{
contentType = "application/msword";
}
int nFileLen = Image.ContentLength;
byte[] myData = new byte[nFileLen];
Image.InputStream.Read(myData, 0, nFileLen);
Connection con = new Connection();
con.conopen();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', Document=#Doc, FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, con.conopen());
sqlcom.Parameters.AddWithValue("#Doc", myData);
sqlcom.ExecuteNonQuery();
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
}
else
{
Connection conn = new Connection();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
sqlcom.ExecuteNonQuery();
}
}
You are updating the values of Textboxes from database in your Page_Load. Every time page is posted back it gets values from database and sets in TextBoxes. You need to add a check and only update values and set to TextBoxes if page is loaded first time and not posted back. Like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//your code here...
}
}
I know: Order Event of asp.net PreInit -Init -InitComplete -PreLoad -LoadPage -Control events -LoadComplete -PreRender -SaveStateComplete -Render -Unload
Therefore , When u onckick button, Webpage will ispostback. after, call pageload -> EventButton. value of textbox change, because your pageload set value for textbox.
Edit code:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
}
Try to refer to the value Attribute:
TextBox1.Attributes("value")

my update c# code is not working,can i update two relational table at once?

i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here

Pass value from one page to another page and update

I have 2 pages, page 1 include the gridview and I made one linkbutton that passes the ID to another page ( page 2). On page 2 I fill 10 textboxes and I have one button for edit info.
This code is for page 1 :
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbNextPage" runat="server"
PostBackUrl='<%# "~/secure/upst.aspx?id="+ Eval("ID_st") %>'>edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
...
and this is the code for page 2:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtID.Text = Request.QueryString["id"].ToString();
}
SqlConnection con = new SqlConnection(strcon);
string query = "select * from user_st where ID_st = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", stid);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
txtName.Text = dr["name"].ToString();
txtFamily.Text = dr["family"].ToString();
txtAddress.Text = dr["adres"].ToString();
txtHomeTel.Text = dr["home_tel"].ToString();
txtTahsilat.Text = dr["tahsilat"].ToString();
txtTel.Text = dr["celphone"].ToString();
txtEmail.Text = dr["email"].ToString();
txtShoghl.Text = dr["shoghl"].ToString();
txtAge.Text = dr["age"].ToString();
txtFadername.Text = dr["fader_name"].ToString();
txtIDnumber.Text = dr["melli_code"].ToString();
txtShSh.Text = dr["sh_sh"].ToString();
}
protected void btnOk_Click(object sender, EventArgs e)
{
Boolean res = false;
SqlConnection conn = new SqlConnection(strcon);
string famil = txtFamily.Text;
string name = txtName.Text;
string fader = txtFadername.Text;
string tahsil = txtTahsilat.Text;
Double telhome = Convert.ToDouble(txtHomeTel.Text);
string adres = txtAddress.Text;
Double cel = Convert.ToDouble(txtTel.Text);
string email = txtEmail.Text;
Double shsh = Convert.ToDouble(txtIDnumber.Text);
string shoghl = txtShoghl.Text;
int age = Convert.ToInt32(txtAge.Text);
Double melli = Convert.ToDouble(txtIDnumber.Text);
int id = Convert.ToInt32(txtID.Text);
string query = "update user_st set name=#name ,fader_name=#fader ,family=#famil,tahsilat=#tahsil,adres=#adres,home_tel=#telhome,celphone=#cel,email=#email ,sh_sh=#shsh,shoghl=#shoghl,age=#age,melli_code=#melli where ID_st=#id";
SqlCommand cmdup = new SqlCommand(query, conn);
cmdup.Parameters.AddWithValue("#name",name);
cmdup.Parameters.AddWithValue("#fader_name",fader );
cmdup.Parameters.AddWithValue("#family", famil);
cmdup.Parameters.AddWithValue("#tahsilat",tahsil);
cmdup.Parameters.AddWithValue("#adres", adres);
cmdup.Parameters.AddWithValue("home_tel",telhome );
cmdup.Parameters.AddWithValue("#celphone",cel );
cmdup.Parameters.AddWithValue("#email", email);
cmdup.Parameters.AddWithValue("#sh_sh", shsh);
cmdup.Parameters.AddWithValue("#shoghl", shoghl);
cmdup.Parameters.AddWithValue("#age",age );
cmdup.Parameters.AddWithValue("#melli_code", melli);
cmdup.Parameters.AddWithValue("#id", id);
try
{
conn.Open();
cmdup.ExecuteNonQuery();
conn.Close();
res = true;
}
catch (SqlException ex)
{
lblRes.Text = "error" + ex.ToString();
}
if (res)
{
lblResult.Text = "Ok";
}
That is not working so, I tried this:
//cmdup.Parameters.Add("#name", SqlDbType.NVarChar, 50).Value = txtName.Text;
//cmdup.Parameters.Add("#fader_name", SqlDbType.NVarChar, 50).Value = txtFadername.Text;
//cmdup.Parameters.Add("#family", SqlDbType.NVarChar, 50).Value = txtFamily.Text;
//cmdup.Parameters.Add("#tahsilat", SqlDbType.NVarChar, 50).Value = txtTahsilat.Text;
//cmdup.Parameters.Add("#adres", SqlDbType.NVarChar, 150).Value = txtAddress.Text;
//cmdup.Parameters.Add("home_tel", SqlDbType.Char, 10).Value = txtHomeTel.Text;
//cmdup.Parameters.Add("#celphone", SqlDbType.Char, 10).Value = txtTel.Text;
//cmdup.Parameters.Add("#email", SqlDbType.VarChar).Value = txtEmail.Text;
//cmdup.Parameters.Add("#sh_sh", SqlDbType.Char, 10).Value = txtShSh.Text;
//cmdup.Parameters.Add("#shoghl", SqlDbType.NVarChar, 50).Value = txtShoghl.Text;
//cmdup.Parameters.Add("#age", SqlDbType.Int).Value = txtAge.Text;
//cmdup.Parameters.Add("#melli_code", SqlDbType.Char, 10).Value = txtIDnumber.Text;
//cmdup.Parameters.Add("#id", SqlDbType.Int).Value = txtID.Text;
or this :
//SqlCommand cmdup = new SqlCommand("EXEC up_st'" + txtName.Text. + "' , '" + txtFamily.Text + "' , '" + txtTahsilat.Text +"' , '" + txtAddress.Text + "' , '"
// + txtHomeTel.Text + "' , '" + txtTel.Text + "' , '" + txtEmail.Text + "' , '" + txtShoghl.Text + "' , '"
// + txtAge.Text + "' , '" + txtFadername.Text + "' , '" + txtIDnumber.Text + "' , '" + txtShSh.Text + "' , '"
// + txtID.Text + "'", conn);
or this :
/*"update user_st set name='" + txtName.Text + "',fader_name='" + txtFadername.Text + "',family='" + txtFamily.Text + "',tahsilat='" + txtTahsilat.Text + "',adres='" + txtAddress.Text + "',home_tel='" + txtHomeTel.Text + "',celphone='"
+ txtTel.Text + "',email='" + txtEmail.Text + "',sh_sh='" + txtShSh.Text + "',shoghl='" + txtShoghl.Text + "',age='" + txtAge.Text + "',melli_code='" + txtIDnumber.Text + "' where ID_st=" + txtID.Text*/
but it also doesn't work.
You need to move your initial Sql select into the !IsPostback block because what's happening is you are posting back your updates, but Page_Load fires before the textboxes are updated. So everything is working in your initial code, you are just updating it with the initial information. Try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtID.Text = Request.QueryString["id"].ToString();
SqlConnection con = new SqlConnection(strcon);
string query = "select * from user_st where ID_st = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", stid);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
txtName.Text = dr["name"].ToString();
txtFamily.Text = dr["family"].ToString();
txtAddress.Text = dr["adres"].ToString();
txtHomeTel.Text = dr["home_tel"].ToString();
txtTahsilat.Text = dr["tahsilat"].ToString();
txtTel.Text = dr["celphone"].ToString();
txtEmail.Text = dr["email"].ToString();
txtShoghl.Text = dr["shoghl"].ToString();
txtAge.Text = dr["age"].ToString();
txtFadername.Text = dr["fader_name"].ToString();
txtIDnumber.Text = dr["melli_code"].ToString();
txtShSh.Text = dr["sh_sh"].ToString();
}
}
If you really want to reload the stuff from the database, you can pop that query into a function and re-run it after the button click update in the button click function (at the end), but there really is no reason since the textboxes will already have the same info.

Button can't forward me to next page

Following is the code for the button but when I click the button, it does not forward me to the desired page. Is there something wrong with my DataReader loop?
{
SqlConnection connBadge = new SqlConnection("Data Source =localhost;" +
"Initial Catalog = BreastCancer; Integrated Security = SSPI");
connBadge.Open();
SqlCommand cmdfBadge = new SqlCommand("SELECT * FROM Products WHERE pid=1", connBadge);
SqlDataReader dr;
dr = cmdfBadge.ExecuteReader();
while (dr.Read())
{
String pName = dr["pName"].ToString();
String pPrice = dr["pPrice"].ToString();
int b = Convert.ToInt16(pPrice);
int a = Convert.ToInt16(ddQty1.SelectedValue.ToString());
int g = a * b;
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values('" + pName + "', '" + b + "', '" + a + "','" + g + "')";
SqlCommand cmdBadge = new SqlCommand(Badge, connBadge);
cmdBadge.ExecuteNonQuery();
}
dr.Close();
connBadge.Close();
Response.Redirect("Cart.aspx");
}
Use parameter and try sqldata adapter:
{
SqlConnection connBadge = new SqlConnection("Data Source =localhost;" +
"Initial Catalog = BreastCancer; Integrated Security = SSPI");
connBadge.Open();
SqlCommand cmdfBadge = new SqlCommand("SELECT * FROM Products WHERE pid='1'", connBadge);
var dSet = new DataSet();
var dt = new Datatable();
var da = new SqlDataAdapter(cmdfBadge);
da.Fill(dSet);
dt = dSet.Tables[0];
foreach(Datarow a in dt.Rows)
{
String pName = a["pName"].ToString();
String pPrice = a["pPrice"].ToString();
int b = Convert.ToInt16(pPrice);
int a = Convert.ToInt16(ddQty1.SelectedValue.ToString());
int g = a * b;
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values(#Name,#Price,#Quantity,#gPrice)";
SqlCommand cmdBadge = new SqlCommand(Badge, connBadge);
sqlCommand.Addwithvalue("#Name",pName);
sqlCommand.Addwithvalue("#Price",b)
sqlCommand.Addwithvalue("#Quantity",a)
sqlCommand.Addwithvalue("#gPrice",g)
cmdBadge.ExecuteNonQuery();
}
connBadge.Close();
Response.Redirect("Cart.aspx");
}
Regards
Wrap the code with a try/catch statement to see if any exceptions are thrown.
Verify your insert statement, I believe it will fail if the datatypes of your price, quantity and gprice are of type integer:
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values('" + pName + "', '" + b + "', '" + a + "','" + g + "')";
You should not wrap these in quotes, remove the quotes and try again.
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values('" + pName + "', " + b + ", " + a + "," + g + ")";
Try to use descriptive variable names, the using statement and a try-catch statement, in the future.

Categories