update a database from dataset - asp.net

as you see in this code i was update the dataset ds at Button1_Click and i want to update the changes made on that dataset to the database.
if i wrote it at the Button1_Click it is work but when i put exactly the same code at Unnamed1_Click it is not working and i dont know why!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Discount : System.Web.UI.Page
{
DataSet ds = new DataSet();
public void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9"))
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Items", con); // יצירת dataAdapter
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int price;
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text))
{
price = Convert.ToInt32(ds.Tables[0].Rows[i][2]);
price -= price * int.Parse(discountrate.Text) / 100;
ds.Tables[0].Rows[i][2] = Convert.ToString(price);
}
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
//SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_");
//con.Open();
//SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
//SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
//tmpda.Update(ds);
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_86098"))
{
con.Open();
SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
tmpda.Update(ds);
}
}
}

You need to specify the update command for your SqlDataAdapter. Just insert the following code after your commandBuilder instace:
tmpda.UpdateCommand = builder.GetUpdateCommand();

Related

Must declare the scalar variable "#Name"

I have these includes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
My connection string is
public partial class Directory : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=10.4.33.61;Initial Catalog=Bank_Reconciliation;Persist Security Info=True;User ID=****;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
My method to search by string and display in data grid view (naming search button as btnsearch) is
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = "select * from Employee where (Name like '%' + #search + '%') ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("#search", SqlDbType.VarChar).Value = txtsearch.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds,"Name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
I receive the following error:
Must declare the scalar variable "#Name".
Why is this, and how do I fix it?
It might be easier to have the TSQL just use LIKE #search, and handle it when adding the parameter:
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = #"SELECT * FROM Employee WHERE Name LIKE #search";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.AddWithValue("#search", "%" + txtSearch.Text + "%");
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds,"Name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
Change you button click code to this:
protected void btnsearch_Click(object sender, EventArgs e)
{
string str = "select * from Employee where (Name like '%" + #search + "%') ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("#search", SqlDbType.VarChar).Value = txtsearch.Text;
con.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataTable dt = new DataTable();
da.Fill(ds, dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
It puts proper quotes for like operator, and also used DataTable instead of DataSet. You can also use DataSet but here it seems no need for that.

Data not coming in SqlDataReader

Well I am not able to figure out the error.No data is coming in variable SqlDataReader.The data retrieved by variable SqlDataReader is stored in Label2.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=(local);Database=records;User Id=sasfddsf;Password=12345");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select id,name,referencename from records where name = '" + Label1.Text.ToString() + "'", con);
var SqlDataReader = cmd.ExecuteReader();
while (SqlDataReader.Read())
{
Label2.Text += Convert.ToString(SqlDataReader["name"]) + Convert.ToString(SqlDataReader["referenceName"]);
}
SqlDataReader.Close();
}
catch (Exception e1)
{
Label2.Text = "Error: " + e1.Message;
}
finally
{
con.Close();
}
}
}
Try this
SqlCommand cmd = new SqlCommand("select id,name,referencename from records where name = #TextBoxName", con);
com.Parameters.AddWithValue("#TextBoxName",Label1.Text.ToString());
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Label2.Text += Convert.ToString(rdr["name"]) + Convert.ToString(rdr["referenceName"]);
}
rdr.Close();

get value into query from edit mode in gridview

I have a simple gridview, 2 columns. The first column is a numeric value. The second column is based on a selected value from a drop down list. I have the drop down list working, but when I go to update the table, I get an error :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
The offending line is 55
Line 53: {
Line 54: string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
Line 55: string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
and here is the code behind for the webform:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string query = "select distinct Unit from vw_KmartBU";
SqlCommand cmd = new SqlCommand(query);
dlBU.DataSource = GetData(cmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
//dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [Business Unit] = #BU where [Annotation Number] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnoNum);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindData()
{
string query = "select [Annotation Number], [Business Unit] as Unit from vw_GridviewSource";
SqlCommand cmd = new SqlCommand(query);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
}
What I need to do is get the value in first column "Annotation Number" and use it in the where clause of my update. So I would need update vw_GridviewSource set [Business Unit] = 'Accessories' where [Annotation Number] = '123456'
Accessories would have been the selection from the drop down list and 123456 would have been in the text box when I selected that row for editing.
Your gridview is missing DataKeyNames. It may look like:
<asp:GridView ID="gvSummary"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="AnnoNum, MyOtherKey1, MyOtherKey2"
... ... ...
DataKeyNames property is an array of strings. You can find more in MSDN

SQL Connection variable not in the current context

I am a beginner in.NEt and having difficulty using the sql connection in a radio button index changed eventhandler that i defined on the page_load.
Below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Controls
{
public partial class Report_Selection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.HeaderStyle.Font.Bold = true;
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
using (SqlConnection cnn = new SqlConnection("Data Source=DBSW9079;Initial Catalog=Underwriting;Integrated Security=SSPI;"))
{
SqlCommand cmd;
SqlDataReader sdr;
if (!IsPostBack)
{
cmd = new SqlCommand("select Categoryid,CategoryTitle from Report_Category", cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
SelectCategorydlist1.DataSource = sdr;
SelectCategorydlist1.DataTextField = "CategoryTitle";
SelectCategorydlist1.DataValueField = "categoryid";
SelectCategorydlist1.DataBind();
cnn.Close();
}
else
{
//It's a Post back
//make the grid visible and fill it
GridView1.Visible = true;
RadioButtonList1.SelectedValue = "1";
cmd = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description " + "where categoryid != 99999"
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
{
}
}
}
}
void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd1;
SqlDataReader sdr1;
if (RadioButtonList1.SelectedIndex.Equals(1))
{
RadioButtonList1.ClearSelection();
cmd1 = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description "
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr1= cmd1.ExecuteReader();
GridView1.DataSource = sdr1;
GridView1.DataBind();
sdr1.Close();
}
}
}
}
In the above code when i use the cnn sequel connection in the event handler i get an small r
Your query in RadioButtonList1_SelectedIndexChanged appears to be incorrect. There's an and without a where:
Select rptdesc,rptdesctext,categoryid from report_description
and categoryid = ...
^^^ should be WHERE

Asp.net how to correct the error

I'm designing in my web page and image are stored in my database (The project is Photostudio management system)
MY Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace photoshops
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != true )
{
constr = #"Data Source=DEVI\SQLEXPRESS;Initial Catalog =cat; Integrated
Security=SSPI";
cnn.ConnectionString = constr;
try
{
if (cnn.State != ConnectionState.Open)
cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "photoset";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#BillNo", TextBox1.Text);
cmd.Parameters.AddWithValue("#CustomerName", TextBox2.Text);
cmd.Parameters.AddWithValue("#Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#StartDate",Rdbsdate.SelectedDate );
cmd.Parameters.AddWithValue("#EndDate", Rdbddate.SelectedDate );
SqlParameter param0 = new SqlParameter("#Systemurl", SqlDbType.VarChar,
50);
cmd.Parameters.AddWithValue("#Numberofcopies", TextBox7.Text);
cmd.Parameters.AddWithValue("#Amount", TextBox8.Text);
cmd.Parameters.AddWithValue("#Total", TextBox9.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new applicationException("!!!! An error an occured while
//inserting record."+ex.Message)
}
finally
{
da.Dispose();
cmd.Dispose();
cnn.Close();
cnn.Dispose();
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Photo setting sucessfullY";
}
else
{
Msg.Text = "photosetting failled";
}
}
}
}
}
}
My ERROR
The record are not stored and image is not stored how to change in my code .
Well first of all, you're not saving the image, you're saving the path of your computer.
You need to save the byte array of the photo.
In short:
Upload its the upload control where you select the image
pic its the byte arrey where you upload the binary content of the photo
and then you only send it as a simple parameter cmd.Parameters.Add ("#pic", pic);
public void OnUpload(Object sender, EventArgs e)
{
// Create a byte[] from the input file
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new
SqlConnection (#"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Image "
+ "(Picture, Comment) values (#pic, #text)", connection);
cmd.Parameters.Add ("#pic", pic);
cmd.Parameters.Add ("#text", Comment.Text);
cmd.ExecuteNonQuery ();
}
finally
{
connection.Close ();
}
}
here are some tutorials, the first link it's very straightforward and the code its simple
http://www.codeproject.com/KB/web-image/PicManager.aspx
another, just in case:
http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/
Principal resource: http://www.codeproject.com/KB/web-image/PicManager.aspx

Resources