Springerdude11
Springerdude11

Reputation: 37

link data from Textbox to SQL Database in ASP.net (C#)

I am attempting to create a web form where data from several text box's will enter data into a n SQL database I have created. My code is listed below, and the problem is that when it compiles, it acts as if it hasn't. The messagedisplay.text does not change, and the SQL database does not update. Does anyone know a solution?

protected void createButton_Click(object sender, EventArgs e)
    {
        string state = stateTextBox.Text;
        string country = countryTextBox.Text;
        string lake = lakeTextBox.Text;



         SqlConnection connection = new SqlConnection("Data Source=.MetricSample;Initial Catalog=ElementID;"+ "Integrated Security=true;");

         connection.Open();
            try
            {
                using (SqlCommand command = new SqlCommand(
                    "INSERT INTO ResearcherID VALUES(@ResearcherFname, @ResearcherLName)", connection))
                {
                    command.Parameters.Add(new SqlParameter("ResearcherFName", country));
                    command.Parameters.Add(new SqlParameter("ResearcherLName", state));
                    command.ExecuteNonQuery();
                }
                messageDisplay.Text = "DB Connection Successfull";
            }
            catch
            {
               messageDisplay.Text = "DB Connection Failed";
            }




    }

Upvotes: 0

Views: 2329

Answers (1)

huMpty duMpty
huMpty duMpty

Reputation: 14460

try this

using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO ResearcherID (FieldNameForFirstName, FieldNameForLastName) VALUES (@ResearcherFname, @ResearcherLName)", sqlConn)) {                  

            sqlCmd.Parameters.AddWithValue("@ResearcherFname", country);  
            sqlCmd.Parameters.AddWithValue("@ResearcherLName", state);  
       }

Also use connection.Open(); inside try

Upvotes: 1

Related Questions