locked
How to get Gridview column data into comma separated string RRS feed

  • Question

  • User-775831949 posted

    I have a Gridview displaying a single column like this

    US
    UK
    Germany

    I need to get this column of data into comma separated string with quotations

    "US,UK,Germany"

    How to do it in RowDataBound event ?

    Thanks

    Friday, January 5, 2018 1:40 PM

Answers

  • User475983607 posted

    It is always best to explain the actual problem you are trying to solve rather that how you think it should be solved and supply your source code in case there is a simple bug or misunderstanding.  IMHO, it is always a bad idea to rely on ViewState persistence and a GridView control because you end up needing multiple events.  In this case, RowDataBound builds and array. Another event like DataBound signals the binding is done and we can go ahead and build the CSV string.

    A much better approach is to create a data layer and query the DB.  The DB is always the system of record and will always contain most the up-to-date data.  When you rely on a GridView, you must also be aware of the event order to make sure you have the most recent data bound to the grid.  Plus the design is much harder to maintain.

    Anyway, here is an example that solves the problem statement as I understand it.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo3.aspx.cs" Inherits="WebFormsDemo.GridViewDemo3" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="Countries" runat="server" OnRowDataBound="Countries_RowDataBound" OnDataBound="Countries_DataBound" AutoGenerateColumns="False">
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="Id" />
                        <asp:TemplateField HeaderText="Item">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Item") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Item") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
            <div>
                <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
            </div>
        </form>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo
    {
        public partial class GridViewDemo3 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
    
                    // Create a new table.
                    DataTable taskTable = new DataTable("Items");
    
                    // Create the columns.
                    taskTable.Columns.Add("Id", typeof(int));
                    taskTable.Columns.Add("Item", typeof(string));
    
                    //Add data to the new table.
                    for (int i = 0; i < 10; i++)
                    {
                        DataRow tableRow = taskTable.NewRow();
                        tableRow["Id"] = i;
                        tableRow["Item"] = "Item " + (10 - i).ToString();
                        taskTable.Rows.Add(tableRow);
                    }
                    Countries.DataSource = taskTable;
                    Countries.DataBind();
    
                }
            }
    
            List<string> items = new List<string>();
            protected void Countries_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    items.Add(((Label)e.Row.FindControl("Label1")).Text);
                    
                }
            }
    
            protected void Countries_DataBound(object sender, EventArgs e)
            {
                Label2.Text = string.Join(",", items);
            }
        }
    }

    To include the double quote in the string...

            protected void Countries_DataBound(object sender, EventArgs e)
            {
                //Label2.Text = string.Join(",", items);
                string stringWithQuote = string.Format(@"""{0}""", string.Join(",", items));
                Label2.Text = stringWithQuote;
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 5, 2018 3:09 PM
  • User-1716253493 posted
            DataTable dt = (SqlDataSource1.Select(new DataSourceSelectArguments()) as DataView).Table;
            List<string> lst = new List<string>();
            foreach(DataRow row in dt.Rows )
            {
                lst.Add(row[0].ToString());
            }
            string result = string.Join(",", lst);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 6, 2018 3:31 AM

All replies

  • User475983607 posted

    It is always best to explain the actual problem you are trying to solve rather that how you think it should be solved and supply your source code in case there is a simple bug or misunderstanding.  IMHO, it is always a bad idea to rely on ViewState persistence and a GridView control because you end up needing multiple events.  In this case, RowDataBound builds and array. Another event like DataBound signals the binding is done and we can go ahead and build the CSV string.

    A much better approach is to create a data layer and query the DB.  The DB is always the system of record and will always contain most the up-to-date data.  When you rely on a GridView, you must also be aware of the event order to make sure you have the most recent data bound to the grid.  Plus the design is much harder to maintain.

    Anyway, here is an example that solves the problem statement as I understand it.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo3.aspx.cs" Inherits="WebFormsDemo.GridViewDemo3" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="Countries" runat="server" OnRowDataBound="Countries_RowDataBound" OnDataBound="Countries_DataBound" AutoGenerateColumns="False">
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="Id" />
                        <asp:TemplateField HeaderText="Item">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Item") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Item") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
            <div>
                <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
            </div>
        </form>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo
    {
        public partial class GridViewDemo3 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
    
                    // Create a new table.
                    DataTable taskTable = new DataTable("Items");
    
                    // Create the columns.
                    taskTable.Columns.Add("Id", typeof(int));
                    taskTable.Columns.Add("Item", typeof(string));
    
                    //Add data to the new table.
                    for (int i = 0; i < 10; i++)
                    {
                        DataRow tableRow = taskTable.NewRow();
                        tableRow["Id"] = i;
                        tableRow["Item"] = "Item " + (10 - i).ToString();
                        taskTable.Rows.Add(tableRow);
                    }
                    Countries.DataSource = taskTable;
                    Countries.DataBind();
    
                }
            }
    
            List<string> items = new List<string>();
            protected void Countries_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    items.Add(((Label)e.Row.FindControl("Label1")).Text);
                    
                }
            }
    
            protected void Countries_DataBound(object sender, EventArgs e)
            {
                Label2.Text = string.Join(",", items);
            }
        }
    }

    To include the double quote in the string...

            protected void Countries_DataBound(object sender, EventArgs e)
            {
                //Label2.Text = string.Join(",", items);
                string stringWithQuote = string.Format(@"""{0}""", string.Join(",", items));
                Label2.Text = stringWithQuote;
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 5, 2018 3:09 PM
  • User-775831949 posted
    Thanks for informing it is not good to use Gridview.

    . How to do it if I have sqldatasouce1 instead?
    Friday, January 5, 2018 3:47 PM
  • User-1716253493 posted
            DataTable dt = (SqlDataSource1.Select(new DataSourceSelectArguments()) as DataView).Table;
            List<string> lst = new List<string>();
            foreach(DataRow row in dt.Rows )
            {
                lst.Add(row[0].ToString());
            }
            string result = string.Join(",", lst);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 6, 2018 3:31 AM