InsertCommand inside of code behind - asp.net

I came across the followng code in the code behind and wondering
if this may be a good practice in terms of inserting a record
programmatically:
protected void ButtonMain_Click(object sender, EventArgs e)
{
string sConn = ConfigurationManager.ConnectionStrings["SQL1"].ConnectionString;
SqlDataSource dbQ = new SqlDataSource();
dbQ.ConnectionString = sConn;
dbQ.InsertCommand = "INSERT INTO data1_DropDownLists (ParamID, ddlValue) VALUES ('" + ddlAllParams.SelectedValue + "','" +
txtddl.Text + "')";
dbQ.Insert();
DropDownGrid.DataBind();
dbQ = null;
}
What I have seen is before is something like:
string query = "INSERT INTO data1_DropDownLists vALUES ...";
cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
so was not sure of what the benefit may be to using the above method using InsertCommand

The SqlDataSource is a control in the System.Web namespace. It can be used as datasource for web-databound controls like Repeater or GridView.
It is a control which should be used declaratively on the aspx markup and not in codebehind. It's like an interface between the GUI and the DAL. Normally you should avoid this kind of hardlinking. Instead you should separate GUI(ASPX), BLL(codebehind or class libraries etc.) and DAL (ADO.NET or Entity framework etc.).
I would suggest to use the most direct way, using an ADO.NET SqlCommand:
// use using-statement to ensure that the connection gets closed even in case of an error
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("INSERT INTO dbo.Table(Column)VALUES(#Column)", con))
{
// use parameters to avoid SQL-Injection
cmd.Parameters.AddWithValue("#Column", value);
con.Open();
cmd.ExecuteNonQuery();
}
}

The SqlDataSource class has four command properties, one for each sql action: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand.
Once an instance is created, each of the command property can be set.
The class also exposes a two arguments constructor SqlDataSource(String, String) where the second argument specifies the SELECT command text.

Related

Can't Update Database from ASP.NET Webform

I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler

Incorrect syntax near '='

It gives an error when I run this code, help me to resolve this error.
Incorrect syntax near '='.
my question about what kind error is this.?
namespace SqlCommandBuilders
{
public partial class WebForm1: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
string sqlQuery = "Select * from tblStudents where ID = "+txtStudentID.Text;
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds, "Students");
ViewState["SQL_QUERY"] = sqlQuery;
ViewState["DATASET"] = ds;
if(ds.Tables["Students"].Rows.Count > 0)
{
DataRow dr = ds.Tables["Students"].Rows[0];
txtStudentID.Text = dr["Name"].ToString();
txtTotalMarks.Text = dr["TotalMarks"].ToString();
ddlGender.SelectedValue = dr["Gender"].ToString();
}
else
{
lblStatus.ForeColor= System.Drawing.Color.Red;
lblStatus.Text = "No Student Record with ID =" + txtStudentID.Text;
}
}
}
}
Think about the string you're creating for a moment. Suppose txtStudentID.Text is the string Joe. You'd be creating Select * from tblStudents where ID = Joe which is obviously incorrect. Joe needs quotes around it.
But, don't just put quotes around it. Here's why:
The correct thing to do is use a parameterized statement, as described on here the site linked above. Applying their example to your code, we'd get something like:
SqlCommand sqlQuery = new SqlCommand("Select * from tblStudents where ID = #username", con);
sqlQuery.Parameters.AddWithValue("#username", txtStudentID.Text);
...but I don't know what your ViewState thing is, so can't help you apply it there.
SQL commands that use text input by users should almost ALWAYS use parameterized queries to avoid SQL injection attacks and syntax errors, and it's also good to get in the habit of wrapping disposable objects (like database connections) in using statements:
DataSet ds = new DataSet();
using(SqlConnection con = new SqlConnection(CS)) {
string sqlQuery = "Select * from tblStudents where ID = #studentId";
using(SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con)) {
da.SelectCommand.Parameters.Add("#studentId", SqlDbType.VarChar)
.Value = txtStudentID.Text;
da.Fill(ds, "Students");
}
}
A couple things here.
SQL parameters should always be used in cases such as this.
Also, Is Student ID a text field in the database or a number?
If its a numeric, where is the textbox being initialized? The page_load is one of the first things that happen, and since you are running this on all page_loads (even the first time), if its an empty string, it'll definitely crash regardless of whether you use parameters or not, because an empty string cannot be converted to a number.

why doesn't the c# update query for storedprocedure work?

This question arises out of a net article to insert and update a row of a GridView in a popup window. here.
Clicking on the edit button in GridView, you get a popup window for edit. You edit the window and click 'save' to save it in database. the save method is :
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "AddUpdateCustomer";
cmd.CommandText = "UPDATE [Customers] SET [CompanyName] = #CompanyName ,[ContactName] = #ContactName WHERE CustomerID = #CustomerID";
cmd.Parameters.AddWithValue("#CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("#ContactName", txtContactName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtCompany.Text);
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
cmd.ExecuteNonQuery();
}
}
The online article used the commented line for cmd.CommandText which I changed as that did not work nor did I find its utility. I also added the last line cmd.ExecuteNonQuery(); to execute the query But actually no change in DB.
What might be wrong with the Save method and how to deal with that wrong ?
You've requested a call to a stored procedure, but the line you commented-out is the one that contains the stored procedure name.
It looks like you're actually executing raw SQL so you should try instead:
cmd.CommandType = CommandType.Text;
But your CommandText line won't work either because it isn't real SQL. It needs to include the content of the variables rather than the variable names. And also you should be executing a query rather than a non-query.
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Concat("UPDATE [Customers] SET [CompanyName] = ", txtCompany.Text, ", [ContactName] = ", txtContactName.Text, " WHERE CustomerID = ", txtCustomerId.Text, ";");
etc
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}
this is because on every postback asp.net will save the controls value in viewstate and when page return from server controlls are filled with old value and database table will update with old value rather than new value

binding dropdownlist in asp.net

i have a Class called "Services" in the App_code folder that contain Method like this:
public static ???? GetAllCustomers()
{
string conn = ConfigurationManager.ConnectionStrings["ConnectToDB"].ConnectionString;
using (SqlConnection connection= new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select C_ID,L_ID,C_Name from Customer";
cmd.Connection = connection;
connection.Open();
????
????
}
}
return ???;
what should i use in the "????" as return type...because i want to bind dropdownbox.datasource to ???? and use the datavaluefield and datatextfield..
so should i make the method return datatable class or something else..
i hope i made my question clear..
You can return a System.Data.DataTable and use column names for datatextfield and datavaluefield.
If you're going to write it with so much specificity (i.e., it's tailored to one specific dropdown, not abstracted to the point that it can be used by any other dropdown), then instead of a function, make it a sub (void? -- no return type in any case). There's only two addtional steps to add then -- set the dropdown's datasource, and then call databind.
So then, you'd just call the sub each time you wanted to populate the dropdown.
If you want to abstract it a little more, so that it takes parameters for commandtext, or what have you, then a function would be a good idea. In that case, datatable would be a good return type.

ASP.NET store Image in SQL and retrieve for Asp:Image

I am looking to fileupload a picture jpeg,gif,etc into an SQL database on an updateprofilepicture page. Then on the profile page, I want to retrieve the image from an sql database and have it show up in an Asp:Image control. I have much code trying to do this and it doesn't work. The table contains a column of type Image.
As Joel mentioned you should use an HttpHandler or a page to display the image. Here is a sample code to output image (Image.ashx) :
// ProcessRequest method of Image.ashx
long imageId = Convert.ToInt64(Request.QueryString["ImageId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImageID", conn))
{
command.Parameters.Add("#ImageID", SqlDbType.Int).Value = imageId;
conn.Open();
Response.ContentType = "image/gif";
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Image1" runat="server" ImageUrl="Image.ashx?ImageID=12"/>
The important thing to remember here is that you shouldn't try to transmit the image data with the profile page itself. Instead, you want your profile page to generate HTML markup for the browser that looks something like this:
<img src="~/MyImageHandler.ashx?UserID=1234" alt="User 1234 avatar" width="100px" height="150px" />
That is the ultimate result of your <asp:Image .../> control. Then the browser will send a completely separate Http request to retrieve the image. That's how pictures on web sites work. You then need to be able to handle that additional request. To do that, create an Http handler (*.ashx file) and use it to retrieve the appropriate image data from the database and send it to the browser.
If you're using SQL 2005 or greater you should not use the data type Image because it's now deprecated. Instead you want to use the new Varbinary(MAX) type if possible. Once you have it stored all you need to do is retrieve it via ADO.Net call and cast the cell value into type Byte[] and then call Response.BinaryWrite like in ScarletGarden's example above.
After a few hundred gigabytes of images, I believe you'll find yourself thinking that the operating systems' file system and static file http servers is better suited than the database, which is busy which a lot of other details, for storing images. It also allows you to use thousands of existing free tools to work with, move, host, etc the images.
Instead of storing images in the database, store the path and/or filename for the image. Images will fill up the database and make it slow.
protected void Page_Load(object sender, EventArgs e) {
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e) {
string strImageName = txtImageName.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=RND3" + "\\" + "SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True";
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Imagess(ImageName,Image)" + " VALUES (#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName = new SqlParameter("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "File Uploaded";
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
con.Close();
}
}
Try these links it might help you..
you can also try by storing the image files on the server and store the paths on the Sql table..
by these links
http://pratikataspdotnet.blogspot.in/2014/11/retrieve-images-from-path-stored-in.html

Resources