Monday, March 26, 2012

How to save contents of Text box to database?

Hi,

For some reason I can't use the edit, update or insert features on my remote shared server, so I am looking to create a web page that has text boxes on it, that I can enter data into, that will be saved into my database.

This is opposed to entering the data directly into the database itself. I want to be able to use a webpage, for simply adding new data, and saving it so that the new data updates and saves over the top of the old data.

What are the steps involved in doing this?

Any example code for just one text box would be appreciated, I could then extend it to suit my needs. Tia.

As I understand you want to get data in text box in you website and then update or insert to the database table. Here I wrote a very simple sample in C#:

protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = @."Data Source=Confute\SQL2000;Initial Catalog=tempdb;Integrated Security=SSPI;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
// Connect to the database then retrieve the schema information.


SqlCommand cmd = new SqlCommand("sp_UpdateMytable", connection);
connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@.id", txtBox_ID.Text);
cmd.Parameters.Add("@.name", txtBox_Name.Text);
int i = cmd.ExecuteNonQuery();

}

And the storedprocedure sp_UpdateMytable will update a table t1(id int, name varchar(30)) in this way:


create proc sp_UpdateMyTable @.id int,@.name varchar(30)
as
if exists (select * from t1 whereid=@.id)
update t1 setname=@.namewhere id= @.id
else insert into t1 select @.id,@.name
go

|||

Thanks Lori_Jay,

I actually resolved the issue and did switch the answered tag on this thread. I am sure your solution would work, however mine was a more simple issue, actually I will mention it here for other poor souls who struggle with the same issue I did.

Basically, I did not have a Primary Key set in my table of my database. Firstly, I was taught that although its a good idea to have a PK, it's not absolutely necessary. Because I had one table, with one column and one row, Idecided not to have one.

If you don't have one, then in Visual Studio 2005, you cannot access the Advanced SQL options, which are INSERT, UPDATE & DELETE, this seems to be a major fault if you ask me because there is ZERO error reporting and ZERO documentation about it.

I got lucky when I did a Google for it (after a week of endless suffering) to find one site in the entire world, written in Russian (which I had to translate very poorily), which stated that you need a PK. I quickly added a PK to my table and it worked instantly.

Perhaps the powers that be whom monitor these forums, can look into this and document it so that others are spared the same distress.

Regards.

No comments:

Post a Comment