DataList 实现 行转列

CSDN 问题原帖

http://topic.csdn.net/u/20090413/10/6e7fad41-9c92-4f06-b1b5-f27b499115c8.html?seed=1772599945

 

行转列的情况很容易遇到,一般都是在SQL中用 case 来解决这类问题,但有时候我们会需要知道列数并做一些事情。

这时,DataList 就发挥它的作用了。主要应用的就是它的RepeatDirection 属性.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataList.aspx.cs" Inherits="temp_DataList" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> 名称:<asp:TextBox ID='txtName' runat="server"></asp:TextBox>     金额:<asp:TextBox ID='txtMoney' runat="server"></asp:TextBox>     <asp:Button ID="btnAdd" runat="server" Text="增加" OnClick="btnAdd_Click" /> <asp:DataList id='dl' runat="server"> <AlternatingItemTemplate> <asp:Literal ID="lit" runat="server" Text='<%#Eval("Name") %>'></asp:Literal> <asp:TextBox ID="txt" runat="server" Text='<%#Eval("Money") %>'></asp:TextBox> </AlternatingItemTemplate> <ItemTemplate> <asp:Literal ID="lit" runat="server" Text='<%#Eval("Name") %>'></asp:Literal> <asp:TextBox ID="txt" runat="server" Text='<%#Eval("Money") %>'></asp:TextBox> </ItemTemplate> </asp:DataList> </form> </body> </html>

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class temp_DataList : System.Web.UI.Page { private DataTable getDateTable() { DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Name", typeof(String))); dt.Columns.Add(new DataColumn("Money", typeof(Int32))); DataRow dr; dr = dt.NewRow(); dr[0] = "岗位工资"; dr[1] = 100; dt.Rows.Add(dr); dr = dt.NewRow(); dr[0] = "养老"; dr[1] = 200; dt.Rows.Add(dr); dr = dt.NewRow(); dr[0] = "午餐"; dr[1] = 300; dt.Rows.Add(dr); return dt; } private void DataListBind(DataTable dt) { int column = dt != null ? dt.Rows.Count : 0; column = column > 6 ? 6 : column;//样式的原因,控制最多6个 dl.RepeatColumns = column; dl.RepeatDirection = RepeatDirection.Horizontal; dl.DataSource = dt; dl.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["dt"] = getDateTable(); DataListBind(ViewState["dt"] as DataTable); } } protected void btnAdd_Click(object sender, EventArgs e) { DataTable dt = ViewState["dt"] as DataTable; if (dt != null) { DataRow dr; dr = dt.NewRow(); dr[0] = txtName.Text.Trim(); int money; int.TryParse(txtMoney.Text, out money); dr[1] = money; dt.Rows.Add(dr); DataListBind(dt); } } }

你可能感兴趣的:(DataList 实现 行转列)