locked
Data in Gridview RRS feed

  • Question

  • User-1499457942 posted

    Hi

       I have Database Structure like below

    Code             Name1           Name2          Name3

    1                   ABC                DEF               GHI

    In Gridview i want to display Name1 , Name2 , Name3 as separate rows like below

    ABC

    DEF

    GHI

    Thanks

    Wednesday, December 19, 2018 11:43 AM

Answers

  • User-1174608757 posted

    Hi JagjitSingh
    According to your description,I have made a sample here. I suggest you to use unpivot in sqlserver to change the columns to rows.
    Here is my code,I hope it can help you.

    Structure database:

    Gridview.aspx:

    head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" runat="server"></asp:GridView>
            </div>
        </form>
    </body>
    

    Gridview.aspx.cs:

    public partial class gridview : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    string sql = "select code,name,namevalue from structure unpivot (namevalue for name in (Name1, Name2, Name3) ) unpiv";
                    string conStr = ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;
                    DataTable dt = new DataTable();
                    using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conStr))
                    {
               
                        adapter.Fill(dt);
    
                    }
    
                    this.GridView1.DataSource = dt;
                    this.GridView1.DataBind();
    
                }
            }
    }
    

    It shows as below

    Best Regards

    Wei Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 20, 2018 2:08 AM