Friday, January 27

Add a column to a sql server table with a asp.net form

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <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>
</body>
</html>

code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnAddColumn_Click(object sender, EventArgs e)
    {

        {
            string alterSQL;
            alterSQL = "ALTER TABLE TestTable ";
            alterSQL += "ADD " + txtIP_TextField.Text + " BIT";
           // alterSQL = String.Format("ALTER TABLE TestTable  ADD {0} BIT",
                                //txtIP_TextField.Text);
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString.ToString());
            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();
            }
        }
    }
}

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty