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!");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With