user3701678
user3701678

Reputation: 11

How to insert values from a masked textbox to the database?

I have used this code but showing me the error

The input string was not in correct Format

Code:

 SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["String"].ConnectionString);

 try
 {
    con.Open();

    SqlCommand com = new SqlCommand("insert into TableYear where textBoxYear=" + int.Parse(maskedTextBox1.Text) + ";", con);

    SqlDataReader reader = com.ExecuteReader();

    int count = 0;

    while (reader.Read())
    {
        count++;
        string AY = reader.GetString(0);
        comboBoxAY.Items.Add(AY);
    }
    con.Close();
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

Upvotes: 1

Views: 2960

Answers (3)

Zeeshan
Zeeshan

Reputation: 3024

The problem isn't regarding insertion of masked textbox' content to database. The problem actually occurs while parsing your masked text to int. here:

int.Parse(maskedTextBox1.Text)

you probably having a masked number in your textbox as 123-34-233 etc. in this case, you first need to clean the string. (i.e, remove spaces, dashes, and all other characters except digits (ints)). if you try to convert 235-145_234 like text to int, using int.Parse(maskedTextBox1.Text), it will obviously give an exception saying input string was not in correct format. because - cannot be parsed to integer.

Try to remove dashes from the string first, and then parse it to int. as:

string textBoxText = maskedTextBox1.Text;
textBoxText = textBoxText.Replace("-", "");
int number = int.parse(textBoxText);

and then insert it to database.

Upvotes: 2

Sunil
Sunil

Reputation: 150

Your INSERT Query is not correct, kindly remove where clause from INSERT statement

Upvotes: 1

marc_s
marc_s

Reputation: 754348

The INSERT in T-SQL doesn't support a WHERE clause - you should use something like:

INSERT INTO dbo.TableYear(Col1) VALUES(Val1)

In C#, you should always use a parametrized query to avoid SQL injection attacks:

SqlCommand com = new SqlCommand("INSERT INTO dbo.TableYear(ColumnName) VALUES(@Value)");

com.Parameters.Add("@Value", SqlDbType.Int).Value = int.Parse(maskedTextBox1.Text);

Also you need to use .ExecuteNonQuery() for INSERT, UPDATE or DELETE commands since those statements don't return a result set:

com.ExecuteNonQuery();

Upvotes: 2

Related Questions