【问题标题】:drop down list with value from database带有数据库值的下拉列表
【发布时间】:2016-07-06 08:29:38
【问题描述】:

我是 C# asp.net web 表单的新手,搜索所有的线索,但我没有答案。

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; //read from web.config.
SqlConnection con = new SqlConnection(constr);
DataTable dt = new DataTable();
con.Open();
SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("select * from gender", con);
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
    ddlmarrital.DataSource = myReader;         //assigning datasource to the dropdownlist
    ddlmarrital.DataTextField = "field";       // text field name of table dispalyed in dropdown
    ddlmarrital.DataValueField = "ID";         // to retrive specific  textfield name 
    ddlmarrital.DataBind();                    //binding dropdownlist
}
con.Close();

table1(性别)1.male 2.female.

Mastertable1(姓名“ABC”)。(性别“男”)。(地址“ABC”)

我想显示一个已保存的值 (Mastertable1.gender),如果我想更改该值,我可以使用下拉列表进行选择。

【问题讨论】:

  • 删除循环。不需要,但是有什么问题?
  • 我无法将“Mastertable1”.gender 上的值显示在下拉列表中。
  • 但是如果您需要 MasterTable 中的值,那么为什么要查询 Gender 表呢?
  • 您能说得更具体些吗?目前的结果是什么?如果可能,请发布屏幕截图。
  • 嗨史蒂夫,可能是我使用了错误的方法。我打算在该字段上显示 mastertable 值。如果我想更改,我可以更改为 table1 中的值。

标签: c# asp.net


【解决方案1】:

您可以尝试以下方法。我对您的代码进行了一些重构,并为SqlConnectionSqlCommand 对象使用了using 语句,因为它们都实现了IDisposable 接口。具体来说,他们使用非托管资源和这些资源,这些资源应该在您完成工作后尽快释放。这就是应该调用Dispose 方法的原因。一种方便的方法是使用using 语句,如下所示。

string connectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 

using(var connection = new SqlConnection(connectionString))
{
    connection.Open();

    var commandText = "SELECT * FROM gender";

    using(var command = new SqlCommand(commandText,connection))
    {
        ddlmarrital.DataSource = command.ExecuteReader();
        ddlmarrital.DataTextField = "field";       
        ddlmarrital.DataValueField = "ID";  
        ddlmarrital.DataBind();         
    }
}

【讨论】:

  • 感谢 Christos,下拉列表可以正常工作,但是您如何设置从 Mastertable1(Gender "Male) 读取以显示为默认值?
  • 我不明白你。你说的阅读是什么意思?这与默认(选定)值有何关联?如果您只需要后者,请说明清楚。否则,您应该更彻底地解释您在寻找什么。
  • 我想要一个包含 Mastertable1 值的下拉列表。这可能吗,或者我完全错了。
  • Mastertable 是什么?它是您数据库中的表吗?如果是,那么为什么在您的 sql 语句中使用名为 gender 的表?我是对的还是我理解错了?
  • 我正在调用性别表,因为我希望它显示在下拉列表中。 Mastertable 是一个包含性别详细信息的表格。在我的表单上,如果 mastertable 上的性别错误,我想使用下拉列表更改字段。希望我解释正确。谢谢。
【解决方案2】:

从工具箱中将 SqlDataSource 对象拖放到 Web 表单上会更容易。将 Dropdownlist 设置为 sqldatasource 对象并配置 sqldatasource。

如果您必须在代码中执行此操作,请删除您的 while 循环。

...
myReader = cmd.ExecuteReader();
ddlmarrital.DataSource = myReader;                 
ddlmarrital.DataTextField = "field";
ddlmarrital.DataValueField = "ID";
ddlmarrital.DataBind();
con.Close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多