aspx page
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Load all" />
</form>
</body>
web.config
<appSettings>
<add key="localhost" value="dbConnectionString"/>
</appSettings>
<connectionStrings>
<add name="dbConnectionString" connectionString="Data Source=.\SQLEXPRESS; User ID=sa; Password=pswd; Database=testdatas; TimeOut=1 " providerName="System.Data.SqlClient"/>
</connectionStrings>
aspx page.cs
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon;
SqlCommand SqlCmd;
string ConnectionName = "";
string ConnectionString = "";
SqlDataReader SqlDr;
List<string> LstString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write(DateTime.Now.ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ConnectionName = ConfigurationManager.AppSettings["localhost"].ToString();
ConnectionString = ConfigurationManager.ConnectionStrings[ConnectionName].ToString();
sqlcon = new SqlConnection();
SqlCmd = new SqlCommand();
sqlcon.ConnectionString = ConnectionString;
SqlCmd.CommandText = "insert into tbone (name) values (@users)";
SqlCmd.Parameters.AddWithValue("@users",TextBox1.Text);
SqlCmd.Connection = sqlcon;
sqlcon.Open();
SqlCmd.ExecuteNonQuery();
sqlcon.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
ConnectionName = ConfigurationManager.AppSettings["localhost"].ToString();
ConnectionString = ConfigurationManager.ConnectionStrings[ConnectionName].ToString();
sqlcon = new SqlConnection();
SqlCmd = new SqlCommand();
LstString = new List<string>();
sqlcon.ConnectionString = ConnectionString;
SqlCmd.CommandText = "select * from tbone";
SqlCmd.Parameters.AddWithValue("@users", TextBox1.Text);
SqlCmd.Connection = sqlcon;
sqlcon.Open();
SqlDr = SqlCmd.ExecuteReader();
while (SqlDr.Read())
{
LstString.Add(SqlDr["name"].ToString());
}
SqlDr.Close();
sqlcon.Close();
DropDownList1.DataSource = LstString;
DropDownList1.DataBind();
}
}
No comments:
Post a Comment