我的代码中有一点问题。
好吧,我有一个gridview,基本上有8列,有一些数据,填充在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;
}
}
}
以下是webform的代码隐藏:
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),这些列数不应在网络表单中显示。
任何帮助或指示都将受到高度赞赏。
编辑:任何其他机制或逻辑或任何其他方式来实现网格视图的动态绑定也将非常受欢迎。
此致
阿努拉格
答案 0 :(得分:1)
每次只需删除第0列:
for (int i = 0; i < number; i++)
{
dt.Columns.RemoveAt(0);
}
因此,您每次都会删除新的第一列。 您还应该检查输入的数字是否小于9.
答案 1 :(得分:0)
我认为您正在寻找的是“可见”属性。尝试像
这样的东西int colmin = 1//whichever columns you want to make invisible
int colmax = 8
for (int i = colmin; i < colmax; i++)
{
datagridview1.Columns[i].Visible = false;
}
这样会隐藏列,但索引保持不变。
希望有所帮助。 干杯