Add a column to a sql server table with a asp.net form
I am using C# form and need to enter a开发者_JS百科 column name to the "varchar(100)" textbox and submit the form to create a column on the "Products3" table in sql server. I am getting this error "Error Creating column. Incorrect syntax near 'System.Web.UI.WebControls.TextBox'." when I click the Submit button. I am not sure why the SQL statement does not see the textbox. Please help.
========================== FrontPage ===
<form id="form1" runat="server">
<div>
<br /><br />
<asp:button id="IP_TextBtn" onclick="btnAddColumn_Click" runat="server" text="Submit" />
<br />
<br />
<asp:textbox id="txtIP_TextField" runat="server"></asp:textbox>
<br />
<br />
<asp:Label id="lblResults" runat="server" Width="575px" Height="121px" Font-Bold="True"></asp:Label>
<br />
<br />
</div>
</form>
========================= BackPage ===
// Creating the Method for adding a new column to the database
public virtual void btnAddColumn_Click(object sender, EventArgs args)
{
{
string alterSQL;
alterSQL = "ALTER TABLE Products3 ";
alterSQL += "ADD '" + txtIP_TextField + "' bool()";
SqlConnection con = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand(alterSQL, con);
cmd.Parameters.AddWithValue("@txtIP_TextField ", txtIP_TextField.Text);
int SQLdone = 0;
try
{
con.Open();
SQLdone = cmd.ExecuteNonQuery();
lblResults.Text = "Column created.";
}
catch (Exception err)
{
lblResults.Text = "Error Creating column. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
}
You're confused about parameterized queries. txtIP_TextField
is not a parameter to the query, so adding it to the Parameters
collection won't help. Your query should be:
string alterSQL = "ALTER TABLE Products3 ADD @txtIP_TextField BIT";
Edit: It looks like it may not be possible to parameterize this statement. In that case, you will need to use:
string alterSQL = String.Format("ALTER TABLE Products3 ADD {0} BIT",
txtIP_TextField.Text);
However, this is still subject to SQL Injection Attacks, and you will need to "clean" the txtIP_TextField.Text before using it.
Use txtIP_TextField.Text
alterSQL += "ADD '" + txtIP_TextField.Text + "' bool()";
Thats the value of your textbox
Use this:
string alterSQL;
alterSQL = "ALTER TABLE Products3 ";
alterSQL += "ADD @txtIP_TextField bool()";
SqlConnection con = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand(alterSQL, con);
cmd.Parameters.AddWithValue("@txtIP_TextField ", txtIP_TextField.Text);
精彩评论