【发布时间】:2014-02-07 01:22:42
【问题描述】:
我的代码有一个小问题。
好吧,我有一个基本上有 8 列的 gridview,其中包含一些数据,这些数据填充在 Page_Load 上。
我也有一个文本框和一个按钮控件。
用户输入一个数字(不大于gridview的列数),然后点击按钮,gridview必须隐藏这些列数。
我为此编写了一个代码,它有一定的局限性。
下面是 ASPX 代码:
<head><script type="text/javascript">
function Call() {
window.alert('No columns to hide');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
Enter the number of columns:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Customize" />
</div>
</form>
</body>
</html>
下面是 DataAccessLayer.cs 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace SampleDynamicGrid
{
public class DataAccesslayer
{
public static DataTable GetCustomizedEmployees()
{
SqlConnection xconn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnect"].ToString());
SqlDataAdapter da = new SqlDataAdapter("select * from dbo.employee", xconn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
以下是网络表单的代码隐藏:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace SampleDynamicGrid
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = DataAccesslayer.GetCustomizedEmployees();
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int number = Convert.ToInt32(TextBox1.Text);
DataTable dt = DataAccesslayer.GetCustomizedEmployees();
if (number == 0)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "Call();", true);
}
else
{
for (int i = 0; i < number; i++)
{
dt.Columns.RemoveAt(i);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
我面临的问题是: 当从数据表中删除第一列(第 0 个索引)时,数据表会自行重新排列。 例如:
原始数据表
0th 1st 2nd 3rd 4th 5th 6th 7th
A B C D E F G H
删除第0个索引列后,数据表重新排列如下:
0th 1st 2nd 3rd 4th 5th 6th
B C D E F G H
现在 dt.Columns.RemoveAt(1)= 第一个索引列(有数据 C)
同样如果文本框中的数字输入为5,6,7,那么有一个例外
位置 4 没有列,这很好理解。
我知道代码在逻辑上不正确。请高手指教。如果我写,我想要那个
一个数字(1 到 7),这些列数不应在 Web 表单中可见。
任何帮助或指点将不胜感激。
编辑:任何其他机制或逻辑或任何其他方式来实现网格视图的动态绑定也将受到欢迎。
问候
阿努拉格
【问题讨论】:
标签: c# asp.net gridview dynamic