4

This is html form; I want to insert value from this form to my SQL Server table using C#. I try to add, but I do not know how to make correct connection and how to use data from this simple form to add it to database. I am using Microsoft SQL Server Management Studio and I have real database and server

<form id="form1" runat="server">
    <h1> Find and search about any employee in Faten</h1>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    <input id="ID" type="text" />
    <input id="name" type="text" />
    <input id="lname" type="text" />
    <input id="pass" type="text" />

    <input id="Submit1" type="submit" value="submit" />
</form>

This is my C# code

protected void Button1_Click(object sender, EventArgs e)
{
    String query = "INSERT INTO Ruser(ID, Name, Lname, pass) VALUES (@ID, @name, @lanme, @pass);";

    SqlConnection connection1 = new SqlConnection();

    SqlCommand cmd = new SqlCommand(query, connection1);
    cmd.CommandType = CommandType.TableDirect;

    cmd.Parameters.AddWithValue("@Id", "33");
    cmd.Parameters.AddWithValue("@name", "abc");
    cmd.Parameters.AddWithValue("@lanme", "abc");
    cmd.Parameters.AddWithValue("@pass", "abc");

    connection1.Open();
    int result = cmd.ExecuteNonQuery();

    // Check Error
    if (result < 0)
        Console.WriteLine("Error inserting data into database!");
}
1
  • Dan Guzman says: "AddWithValue is Evil" - please read the article and stop using it! Commented May 5, 2019 at 12:01

1 Answer 1

3

you can use this one:

var connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI";
using(SqlConnection openCon=new SqlConnection(connStr))
{
}

Or:

var connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Userid=UserName;Password=Secret";
using(SqlConnection openCon=new SqlConnection(connStr))
{
}

But in the better way you sould save your connectionstring in webconfig or if you use .netcore appsetting file and read it from that.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi hasan I do all of this but still same problem no data added to table Is there any problem in the rest of code as you see above
Mr Hassan has shown correct and very good code. You probably should surround the opening of the connection with a try catch and a using statement.
@ benjamin moskovits yes ofcourse I just want to show about connectionstring but I edit my code and thanks for your attention.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.