【问题标题】:How to show a specific item in dropdownlist based on specific value of a cell of a table-row in asp.net gridview control?如何根据asp.net gridview控件中表格行单元格的特定值在下拉列表中显示特定项目?
【发布时间】:2014-06-30 19:01:57
【问题描述】:

我是 asp.net 的新手。我正在构建一个管理页面,我想通过从数据库表中获取员工的数据在 GridView 中显示它。表有 3 列(id、name、isManager)。 “isManager”列有三个可能的值。这些值为“是”、“否”和“空”。管理员有权通过从下拉列表中选择“是”或“否”来决定让员工成为经理。

此管理页面有一个 GridView 控件,其中包含两个 BoundFiled(即 id 和名称)和一个模板字段(即 DropDownList)。我很难在 DropDownList 中显示“isManager”列值。如果数据库表行在“isManager”列中有“是”,我希望 DropDownList 将选定的值/文本显示为“是”,如果表行中有“否”,则显示“否”并显示一个项目“选择选择”如果table-row 包含一个空值。

我的代码:

 protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
 {
   string query = "select * from tblUsersTable";
   DataSet ds = DataBaseConnectivity.GetData(query);
   GridView1.DataSource = ds;
   GridView1.DataBind();
  }
 }

 // RowDataBound() method

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {
   if (e.Row.RowType == DataControlRowType.DataRow)
     {
       //Find the DropDownList in the Row
      DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
      DataSet ds = DataBaseConnectivity.GetData
                                 ("select distinct [isManager] from tblUsersTable");
      ddlManager.DataSource = ds; 
      ddlManager.DataTextField = "isManager";
      ddlManager.DataValueField = "isManager";
      ddlManager.DataBind();
      ddlManager.Items.Insert(0, new ListItem("Please select","-1"));

      /* After these lines of code i am not finding the right way to implement my logic
        */

帮我弄清楚。

【问题讨论】:

  • 旁注:您应该在调用GridView1.DataBind(); 之前将DataSet 加载到字段中,然后您可以从RowDataBound 访问它,而无需在每一行中都加载它。
  • 谢谢你真的很有帮助。愿上帝保佑(y)

标签: c# asp.net gridview drop-down-menu


【解决方案1】:

您必须使用GridViewRowDataItem 才能访问underyling 记录。然后你可以通过DropDownList.SelectedValue选择正确的项目:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {
   if (e.Row.RowType == DataControlRowType.DataRow)
     {
       //Find the DropDownList in the Row
      DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
      DataSet ds = DataBaseConnectivity.GetData
                                 ("select distinct [isManager] from tblUsersTable");
      ddlManager.DataSource = ds; 
      ddlManager.DataTextField = "isManager";
      ddlManager.DataValueField = "isManager";
      ddlManager.DataBind();
      ddlManager.Items.Insert(0, new ListItem("Please select","-1"));
      DataRow row = ((DataRowView)e.Row.DataItem).Row;
      bool isManager= row.Field<bool>("isManager"); // use the correct type if it's not bool
      ddlManager.SelectedValue = isManager.ToString();

除此之外,我不会在 ASP.NET 中使用像 DataBaseConnectivity 这样的 db-helper 类。它们只是令人讨厌的错误或性能问题的根源,如果您使用静态连接则更是如此。更多信息here.

【讨论】:

  • 谢谢亲爱的。你真的是在帮助人。坚持下去。
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 2019-06-15
  • 2021-11-27
  • 1970-01-01
相关资源
最近更新 更多