Reputation: 19
When writing to an SQL database, I am receiving 'System.Web.UI.WebControls.TextBox' rather than the actual data itself.
upload.aspx.cs file (containing the query):
string query = "INSERT INTO reports (birdname, location, details, image, spotteddata, uploaddata, typeofbird) VALUES ('"+birdnametext+"', 'mygarden', 'some details about how long you waited', ' " + img + "', '10th March 2014','" + dateNow + "', '2')";
upload.aspx (containing the textbox):
<header> Upload </header>
<p> Please fill out the form below to put your item up for sale</p>
<p>
<span>Name of Bird:
<asp:TextBox ID="birdnametext" runat="server"></asp:TextBox> </span>
<br/>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Image ID="Image1" runat="server" />
<br />
Upvotes: 0
Views: 1397
Reputation: 29006
Their are may things you are doing wrong:
...'"+ birdnametext + "' ...
should be ...'"+ birdnametext.Text + "' ...
You can build the command like the following:
string query = "INSERT INTO reports(birdname, location) VALUES(@birdname, @location);
SqlCommand cmd = new SqlCommand("query,con);
cmd.Parameters.Add("@birdname", SqlDbType.VarChar).Value = birdnametext.Text;
cmd.Parameters.Add("@location", SqlDbType.VarChar).Value = "mygarden";
// similarly you can add the rest of columns and parameters
cmd.ExecuteNonQuery();
Upvotes: 2
Reputation: 76547
You need to use the Text
property of a TextBox to access its contents :
... + birdnametext.Text + ...
Parameterization, Not Concatenation
Additionally, when building queries, you do not want to use string concatenation as it can leave you vulnerable to things like SQL Injection and poor syntax. A better approach would be to use parameterization as seen below :
using(var connection = new SqlConnection("{your-connection-string}"))
{
// Notice the use of parameters
var query = "INSERT INTO reports (birdname, location, details, image, spotteddata, uploaddata, typeofbird) VALUES (@birdname, @location', @details, ' @uploadData, @someDate, @now, @x)";
using(var command = new SqlCommand(query, connection))
{
connection.Open();
// Read the bytes of your image here and store in a byte[]
var imageData = File.ReadAllBytes(Image1.ImageUrl);
// Add your parameters
command.Parameters.AddWithValue("@birdName",birdnametext.Text);
command.Parameters.AddWithValue("@location","mygarden");
command.Parameters.AddWithValue("@details","some details about how long you waited");
command.Parameters.AddWithValue("@uploadData",imageData);
command.Parameters.AddWithValue("@someDate","10th March 2014");
command.Parameters.AddWithValue("@now",DateTime.Now);
command.Parameters.AddWithValue("@x",2);
// Execute your query
command.ExecuteNonQuery();
}
}
Upvotes: 1