我是ASP.NET新手,正在转换经典ASP应用程序。我有以下代码填充数据库的下拉列表,然后在选择上运行一些条件语句以影响页面。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
// Global variable for SqlConnection
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// specifying sqlconnection string
con.ConnectionString = "...MY CONNECTION STRING";
{
// Select rows from database where the ItemType field isn't empty. Sort them alphabetically by ItemType
using (SqlCommand cmd = new SqlCommand("SELECT * FROM NF_WhatWasteWhere WHERE ItemType <>'' Order By ItemType"))
{
//Open the connection and populate the dropdown list with ID and Itemtype
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ItemType1.DataSource = cmd.ExecuteReader();
ItemType1.DataTextField = "ItemType";
ItemType1.DataValueField = "BinType";
ItemType1.DataBind();
con.Close();
}
}
// Add a non selectable "Select Item" row at the top of the dropdown list
ItemType1.Items.Insert(0, new ListItem("--Select Item--", "0"));
string BinColour = ItemType1.SelectedValue;
}
}
protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
{
//BinResultTest.Text = ItemType1.SelectedValue;
if (ItemType1.SelectedValue == "Green")
{
BinResultTest.Text = "<div class='greenBin results'><div class='arrow'></div><p> should be disposed of in a <strong>green bin</strong>.</p></div>";
}
else if (ItemType1.SelectedValue == "Black")
{
BinResultTest.Text = "<div class='blackBin results'><div class='arrow'></div><p> should be disposed of in a <strong>black bin</strong>.</p></div>";
}
else
{
BinResultTest.Text = "<div class='noBin results'><div class='arrow'></div><p> should <strong>NOT</strong> be disposed of in a green or black bin.</p></div>";
}
}
}
这样可以正常工作,但如果它在我的web.config文件中使用连接字符串会更好。但是,由于我缺乏ASP.NET(C#)的经验,我不知道如何实现这一点。我已经尝试查看在将SQLDataSource和Gridview控件添加到同一网站中的另一个页面时创建的一些代码,但我不确定如何将其添加到上面的代码隐藏中。
我的web.config连接如下:
<connectionStrings>
<add name="ConnectionString_MYDATABASE" connectionString="...MY CONNECTION STRING"
providerName="System.Data.OleDb" />
</connectionStrings>
非常感谢有关如何从web.config集成连接的任何建议,谢谢。
答案 0 :(得分:1)
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_MYDATABASE"].ConnectionString;
如果您想查看更多详细信息示例 - &gt; MSDN article
另外,如果您想继续学习,还需要在解决方案中构建不同的层。因此,数据访问层上应该与数据库建立连接,因此您不会为每个下拉列表编写相同的代码。这意味着您需要单独的类来访问数据库。这是一个我写了一个简单的数据访问层的问题 - &gt; LINK