Frage

I have a web application asp.net web form. Upon submission of my form everything goes well, however when I retrieve my form back, any text boxes which were blank on submission are holding the values given in the database.

example: if textbox1 has "varchar(10)" in the database and I submit my form with nothing in textbox1, when I retrieve my form back textbox1 will contain 10 blank spaces.

here is an example of the code I use for my insert:

    string Connectionstring = ConfigurationManager.ConnectionStrings["Conn"].ToString();
    SqlConnection objConnection = new SqlConnection(Connectionstring);
    SqlDataAdapter cmd = new SqlDataAdapter();

    objConnection.Open();

    //Command Insert
    cmd.InsertCommand = new SqlCommand("INSERT INTO T_Table Values(@Textbox1);", objConnection);

    cmd.InsertCommand.Parameters.Add("@Textbox1", SqlDbType.NChar).Value = Textbox1.Text;

    cmd.InsertCommand.ExecuteNonQuery();

    //Close connection
    objConnection.Close();

here's how I'm retrieving it:

    string Connectionstring = ConfigurationManager.ConnectionStrings["Conn"].ToString();
    SqlConnection objConnection = new SqlConnection(Connectionstring);

    objConnection.Open();               
    SqlCommand sqlCmd = new SqlCommand("SELECT Textbox1 FROM T_Table WHERE this = '" + this.Text + "'", objConnection);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
    sqlCmd.Parameters.AddWithValue("@Textbox1", Textbox1.Text);

    dt1.Clear();
    sqlDa.Fill(dt1);

    if (dt1.Rows.Count > 0)
    {
        Textbox1.Text = dt1.Rows[0]["Textbox1"].ToString();
    }
    objConnection.Close();
War es hilfreich?

Lösung

Even though it's a VARCHAR in the DB, it looks liek you're adding it as a CHAR:

cmd.InsertCommand.Parameters.Add("@Textbox1", SqlDbType.NChar).Value

Shouldn't it be the following?

cmd.InsertCommand.Parameters.Add("@Textbox1", SqlDbType.NVarChar).Value

Andere Tipps

You don't want to insert blank values into the database. If the textbox is blank, then insert a NULL value. You can do this like so..

if(!string.IsNullOrWhiteSpace(Textbox1.Text))
{
    cmd.InsertCommand.Parameters.AddWithValue("@Textbox1" DBNull.Value);
}
else
{
    cmd.InsertCommand.Parameters.AddWithValue("@Textbox1", Textbox1.Text.Trim());
}

The DBNull.Value will insert 'NULL' into the database.

You will also want to change your insert statements to use AddWithValue like above. I'm a little surprised intellisense didn't tell you that Add is obsolete. Now when you return the values back to the textbox, you shouldn't have any problems.

Hopefully this puts you on the right direction.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top