简体   繁体   English

如何获取 Gridview 列中的不同值并将它们存储到数据表或列表中?

[英]How can I get the distinct values in a Gridview column and store them into a Datatable or list?

I have a Gridview in a C# ASPX Page called Gridview1 that pulls a Table from a SQL Server and displays it on PageLoad.我在名为 Gridview1 的 C# ASPX 页面中有一个 Gridview,它从 SQL 服务器中提取一个表并将其显示在 PageLoad 上。

There are 10 columns in the Gridview and I need all the distinct values in column 7 which is Code Gridview 中有 10 列,我需要第 7 列中的所有不同值,即代码

Code代码

A   
C
D
A
A
D
B
E
R
A
A
C
B

Basically I need some kind of structure, list or even a datatable to get all the distinct values from the Column "Code".基本上我需要某种结构、列表甚至数据表来从“代码”列中获取所有不同的值。 From the example above it would be a list or datatable with 6 entries since there are 6 unique codes in the Gridview column.在上面的示例中,它将是一个包含 6 个条目的列表或数据表,因为 Gridview 列中有 6 个唯一代码。

Distinct AB C DE R不同 AB C DE R

Any ideas how this can be implemented?任何想法如何实现?

Well, ALWAYS but always try to do such code against the data source and NOT the web page HTML (be it a list view, or grid view, repeater or whatever).好吧,总是但总是尝试对数据源而不是 web 页面 HTML 执行此类代码(无论是列表视图,还是网格视图,中继器或其他)。 The web page is for display of the data, not data base stuff. web 页面用于显示数据,而不是数据库内容。

Now, I suppose in this case, we could operate against the grid, but it usually a WHOLE lot easier to operate against the data.现在,我想在这种情况下,我们可以对网格进行操作,但对数据进行操作通常要容易得多。

So, say this grid:所以,说这个网格:

     <div style="float:left;width:40%">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
            CssClass="table table-hover table-striped" 
            DataKeyNames="ID">
        <Columns>
            <asp:BoundField DataField="FirstName"   HeaderText="FirstName"   />
            <asp:BoundField DataField="LastName"    HeaderText="LastName"    />
            <asp:BoundField DataField="City"        HeaderText="City"        />
            <asp:BoundField DataField="HotelName"   HeaderText="HotelName"   />
            <asp:BoundField DataField="Description" HeaderText="Description" />
            <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                <ItemTemplate>
                     <asp:Button ID="cmdDel" runat="server" 
                        Text="Delete" 
                        CssClass="btn"
                        onclick="cmdDel_Click"
                        onclientClick="return confirm('really delete this?');"/>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </div>
    <div style="float:left;margin-left:40px">
        <h4>City list</h4>
        <asp:ListBox ID="ListBox1" runat="server"
            DataTextField="City"
            DataValueField="City" Width="163px" Height="159px"
            ></asp:ListBox>
    </div>
  </div>

So, right next to the grid, I have a list box we will list out each seperate city.所以,在网格旁边,我有一个列表框,我们将列出每个单独的城市。

So, code to load is this:所以,要加载的代码是这样的:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {
        DataTable rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
        GridView1.DataSource = rstData;
        GridView1.DataBind();

        // now fill out a list box of each city
        DataTable rstCity = new DataTable();
        rstCity = rstData.DefaultView.ToTable(true, "City");
        rstCity.DefaultView.Sort = "City";

        ListBox1.DataSource = rstCity;
        ListBox1.DataBind();
    }

And we get this:我们得到了这个:

在此处输入图像描述

So, NOTE how we went to the data source - NOT the grid (the grid is not a database and in most cases we should not think of the grid as such).因此,请注意我们是如何访问数据源的——而不是网格(网格不是数据库,在大多数情况下,我们不应将网格视为这样)。

However, we could also pull the values out of the grid (can't see why we would do this).但是,我们也可以将值拉出网格(不明白我们为什么要这样做)。

So, lets drop in listbox 2, and add this code that operates against the grid:因此,让我们放入列表框 2,并添加对网格进行操作的代码:

our 2nd listbox - this time NOT data bound.我们的第二个列表框 - 这次不是数据绑定。

So, this:所以这:

    <div style="float:left;margin-left:40px">
        <h4>City list 2nd example</h4>
        <asp:ListBox ID="ListBox2" runat="server"
            DataTextField="Text"
            DataValueField="Value"
            Width="163px" Height="159px"
            ></asp:ListBox>
    </div>

And say a button click or whatever - we run this code to fill out 2nd listbox from the data grid.并说单击按钮或其他任何内容-我们运行此代码以从数据网格中填写第二个列表框。

FYI: If you using templated fields, then you have to use findcontrol to get the control.仅供参考:如果您使用模板化字段,那么您必须使用 findcontrol 来获取控件。 If you using data fields, then you use.cells[] array/collection.如果您使用数据字段,则使用 .cells[] 数组/集合。

but, CAUTION, since empty cells will render as a non breaking space &nsb;但是,请注意,因为空单元格将呈现为非中断空间 &nsb;

So, we convert from html, just to be save, and we have this code:所以,我们从 html 转换,只是为了保存,我们有这个代码:

   protected void Button1_Click1(object sender, EventArgs e)
    {
        List<string> CityList = new List<string>();
        foreach (GridViewRow gRow in GridView1.Rows)
        {
            string sCity = Server.HtmlDecode(gRow.Cells[2].Text);
            if (!CityList.Contains(sCity))
                CityList.Add(sCity);
        }
        // display our list in 2nd listbox
        CityList.Sort();
        foreach (string sCity in CityList)
        {
            ListBox2.Items.Add(new ListItem(sCity, sCity));
        }
    }

So, now we have this:所以,现在我们有了这个:

在此处输入图像描述

So try to operatee against the data.所以尝试对数据进行操作。 I mean, we could even say get a list of distinct citys wiht a query, say this:我的意思是,我们甚至可以说通过查询获取不同城市的列表,这样说:

 string strSQL = "SELECT City from tblHotels GROUP BY City";
 Datatable rstCity = MyRst(strSQL);
 ListBox1.DataSource = rstCity;
 ListBox1.DataBind();

So, in most cases??所以,大多数情况下??

Much less effort and better to get this data from the data source, and NOT go to the GV - as it is a display and render system - not a data base, nor is it a data source.从数据源中获取这些数据的工作量要少得多,效果更好,而不是 go 到 GV - 因为它是一个显示和渲染系统 - 不是数据库,也不是数据源。

Now, in above, I used a helper function MyRst.现在,在上面,我使用了一个助手 function MyRst。 All that does is return a table based on sql - (became VERY tired very fast having to type that type of code over and over).所做的只是返回一个基于 sql 的表 - (变得非常累非常快不得不一遍又一遍地键入那种类型的代码)。 So that was this:所以就是这样:

DataTable MyRst(string strSQL)
{
    DataTable rstData = new DataTable();
    using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
    {
        using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
        {
            conn.Open();
            rstData.Load(cmdSQL.ExecuteReader());
        }
    }
    return rstData;
}

暂无
暂无

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

相关问题 如何将值存储在列表或数组中并将所有值绑定到数据表然后 gridview - How to store values in a list or array and bind all to datatable then gridview 从.NET 2.0中的DataTable列中获取不同的值 - Get distinct values from a column of DataTable in .NET 2.0 如何从 DataTable 中获取一列值的列表? - How to get list of one column values from DataTable? 从列表中获取请求的列不同值 - Get requested column distinct values from list 如何以另一个列为条件从DataTable对象中选择不同的列组合? - How can I select distinct column combinations from a DataTable object with another column as a condition? 从数据表中获取不同的值 - Get distinct values from a datatable WPF:如何在运行时将列表视图中的网格视图列的绑定路径更改为数据表的另一列? - Wpf: How can i change the binding path of a gridview column in a listview to another column of a datatable at runtime? 如何将Excel中的列放入DataTable后以大写形式获取它们 - How to get the values from a column in Excel in uppercase after putting them into a DataTable 如何使用 LINQ 从 DataTable 中获取不同的、有序的名称列表? - How do I get a distinct, ordered list of names from a DataTable using LINQ? Gridview:将数据表中的值绑定到控件为下拉列表的列,但不要将其添加到下拉列表 - Gridview: Bind values from datatable to a column where control is dropdownlist but don't add them to dropdownlist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM