简体   繁体   English

将日期绑定到GridView中的下拉列表

[英]Binding dates to dropdownlist inside gridview

I have to bind a label and a drop down in a gridview,the DDL contains rundates that is datetime format i have to show all the different dates in the DDL associated with the name. 我必须绑定一个标签并在网格视图中下拉菜单,DDL包含日期格式的运行日期,我必须在DDL中显示与该名称相关联的所有不同日期。

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = new DataTable();
        dt = Common.rundate();
        DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;

        ddl.DataTextField = "RunDate";
        ddl.DataValueField = "TempID";
        ddl.DataSource = dt;
        ddl.DataBind();
    }

}

Store Proc::  

    alter PROC display_rundates
@rundate datetime,@tempid int
AS
  SELECT RunDate,TempID
    FROM History_Table

ORDER BY Rundate DESC
GO

But i have to show the specific rundates associated with each Name.Any help can be appreciated. 但是我必须显示与每个Name.Any帮助相关的特定运行日期。

Name   rundate
Test   datetime(DDL)
Test1   datetime

Try this 尝试这个

ddl.SelectedValue = ((System.Data.DataRowView)(e.Row.DataItem)).Row["TempId"].ToString();

Basically just get "TempId" from the data item during GridView1_RowDataBound and assign that "TempId" to drop down's Selected value. 基本上,只需在GridView1_RowDataBound期间从数据项中获取“ TempId”,然后将该“ TempId”分配给下拉列表的Selected值。

Something like this 像这样

void bindGrid()
{
   grid.DataSource = getRunDates();
   grid.DataBind();
}
DataTable getRunDates()
{
   DataTable dt = new DataTable();
   dt.Columns.Add("TempID");
   dt.Columns.Add("RunDate");
   dt.Rows.Add(new object[] { 1, "20-May-2012" });
   dt.Rows.Add(new object[] { 2, "21-May-2012" });
   dt.Rows.Add(new object[] { 3, "10-May-2012" });
   dt.Rows.Add(new object[] { 4, "20-May-2012" });
   return dt;
}
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      DataTable dt = new DataTable();
      dt = getRunDates();
      DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;

      ddl.DataTextField = "RunDate";
      ddl.DataValueField = "TempID";
      ddl.DataSource = dt;
      ddl.DataBind();

      ddl.SelectedValue = ((System.Data.DataRowView)(e.Row.DataItem)).Row["TempId"].ToString();
    }
}

Design 设计

<asp:GridView runat="server" ID="grid" OnRowDataBound="grid_RowDataBound" AutoGenerateColumns="false">
   <Columns>
      <asp:TemplateField HeaderText="RunDate">
         <ItemTemplate>
             <asp:DropDownList runat="server" ID="DropDownList1" />
         </ItemTemplate>
       </asp:TemplateField>
      <asp:BoundField HeaderText="TempID" DataField="TempID" />
   </Columns>
</asp:GridView>

When you bind the gridview you must also bind the primary key to some template field control,if you have not written it then add hidden field and bind to it as follow 绑定gridview时,还必须将主键绑定到某个模板字段控件,如果尚未编写,则添加隐藏字段并按以下方式绑定到它

 <ItemTemplate>
            <asp:HiddenField runat="server" ID="hiddenfield1" Value='<%# Eval("TempID") %>' />
            <asp:DropDownList runat="server" ID="ddl" />
 </ItemTemplate>

In RowDataBound Event you can findout the PrimaryKey and then use it to set the Dropdown Selected Value as follow... RowDataBound事件中,您可以找到PrimaryKey,然后使用它来设置Dropdown Selected Value,如下所示...

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = new DataTable();
        dt = Common.rundate();
        DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;

        ddl.DataTextField = "RunDate";
        ddl.DataValueField = "TempID";
        ddl.DataSource = dt;
        ddl.DataBind();

        HiddenField hdn=(HiddenField)row.Cells[cellindex].FindControl("hiddenField1");
        ddl.SelectedValue=hdn.Value;
    }

}

I am still not convinced by my solution, but I think this is the way I would go about it... 我仍然不相信我的解决方案,但是我认为这就是我要解决的方法...

When loading the data in the first time I would fill a dictionary with the run dates for each name: 第一次加载数据时,我会用每个名称的运行日期填充字典:

    private Dictionary<string, List<DateTime>> runDates = new Dictionary<string, List<DateTime>>();

    private void LoadData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("TempName", typeof(string));

        using (var connection = new SqlConnection("YourConnectionString"))
        using (var command = new SqlCommand("SELECT DISTINCT TempName, RunDate FROM History_Table;", connection))
        {
            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    string tempName = reader.GetString(0);
                    if (!runDates.ContainsKey(tempName))
                    {
                        DataRow row = table.NewRow();
                        row[0] = tempName;
                        table.Rows.Add(row);
                        runDates.Add(tempName, new List<DateTime>());
                    }
                    runDates[tempName].Add(reader.GetDateTime(1));
                }
            }

            GridView1.DataSource = table;
            GridView1.DataBind();
        }
    }

When reading each row it checks if the name already exists, if it does not then it adds it to the table that will be used to bind the GridView and to the dictionary. 读取每一行时,它将检查名称是否已经存在,如果不存在,则将其添加到将用于绑定GridView和字典的表中。 Then in the binding event use the name label to find the list of dates from the dictionary: 然后在绑定事件中,使用名称标签从字典中查找日期列表:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Find the label with the temp name and assign it
            string tempName = (e.Row.FindControl("Label1") as Label).Value;

            DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;

            ddl.DataTextField = "RunDate";
            ddl.DataValueField = "TempID";
            ddl.DataSource = runDates[tempName];
            ddl.DataBind();
        }

    }

I toyed with various other ideas, one was returning the date list as an xml field with a unique list of names (much like in your previous question), storing this in a hidden field and deserialising on the row databound event, another solution was to generate 2 tables in the data set and define relationships, but this is very similar in principle to the method I have proposed, and I think I prefer this one... 我玩弄了其他各种想法,一个是将日期列表作为具有唯一名称列表的xml字段返回(类似于您上一个问题),将其存储在一个隐藏字段中,并在行数据绑定事件上反序列化,另一种解决方案是在数据集中生成2个表并定义关系,但这在原则上与我提出的方法非常相似,我想我更喜欢这个方法...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM