【问题标题】:Access the data in Gridview in runtime when it set auto generate?设置自动生成时在运行时访问Gridview中的数据?
【发布时间】:2012-07-21 14:42:58
【问题描述】:

我将我的数据从 Excel 工作表导入到网格视图。之后我想将我的网格视图的列标题文本放入下拉列表中,但我无法访问它们 请帮帮我:-(;

这是我的代码,但它不起作用:

List<string> lst = new List<string>();
* for (int i = 0; i < dg_excel.Columns.Count; i++)
{
    lst.Add(dg_excel.Columns[i].HeaderText);
}
ddl_prd_count.DataSource;
ddl_prd_count.DataBind();

对于这个 * 行,它告诉我没有列 (column.count = 0)

【问题讨论】:

  • 为什么不在数据源上而不是网格上执行循环??
  • dg_excel 的列是自动生成的,如果是,则从其数据源中迭代列名,否则您知道列名。

标签: c# asp.net


【解决方案1】:

在另一个 SO 线程 Why column count is 0 for GridView 上检查 answer 以了解您为什么无法访问网格的 Columns 集合中的列。

在我看来,如果您想使用自动生成的列,请点击此 ASP.net 论坛链接 - Customizing Auto Generated Columns (GridView) 和 SO 线程 How to hide columns in an ASP.NET GridView with auto-generated columns?

例如 从这段代码中有一个想法..我没有检查其中的正确语法等。

 protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        if (IsFillCombo)
        {
            //fill your list here.
            for (int i = 0; i < datasourcetable.Columns.Count; i++)
            {
                lst.Add(e.Row.Cells[i].Text);
            }
            IsFillCombo = false;
        }
    }
} 

// 另一种最简单的实现方式如下:来自Question Text

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Abc> listofAbc = new List<Abc>();
                for (int i = 0; i < 10; i++)
                {
                    listofAbc.Add(new Abc
                    {
                        ID = i + 1,
                        Name = "Abc" + (i + 1).ToString()
                    });
                }
                GridView1.DataSource = listofAbc;
                GridView1.DataBind();

                List<string> lst = new List<string>();

                for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
                {

                    lst.Add(GridView1.HeaderRow.Cells[i].Text);
                    System.Diagnostics.Debug.WriteLine(GridView1.HeaderRow.Cells[i].Text);
                }
            }
        }
    }
    public class Abc
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

【讨论】:

    【解决方案2】:

    您可以使用以下代码

    List<string> lst = new List<string>();
    
    for (int i = 0; i < dg_excel.HeaderRow.Cells.Count; i++)
    {
    
        lst.Add(dg_excel.HeaderRow.Cells[i].Text);
    
    }
    
    ddl_prd_count.DataSource=lst ;
    
    ddl_prd_count.DataBind();
    

    【讨论】:

      【解决方案3】:

      访问您的网格的gridView1_CellValueChanged 事件 然后访问e.Column.FieldName.ToString()

      【讨论】:

        猜你喜欢
        • 2014-02-05
        • 1970-01-01
        • 1970-01-01
        • 2011-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多