我正在通过练习工作,我需要有一系列复选框,这些复选框需要根据检查的数据集更新数据集,目前代码有效,但它删除了复选框而不是添加它们:
ds.Tables[0].Columns.Remove(item.Text);
当我将其更改为此时会破坏代码:
ds.Tables[0].Columns.Add(item.Text);
以下是完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class application_Crosswalk : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Cache.Remove("CrosswalkSPS");
DataSet ds = GetDataSet();
chkColumns.DataSource = ds.Tables["CrosswalkSPS"].Columns;
chkColumns.DataTextField = "ColumnName";
chkColumns.DataBind();
}
}
private DataSet GetDataSet()
{
DataSet ds = (DataSet)Cache["CrosswalkSPS"];
// Contact the database if necessary.
if (ds == null)
{
ds = RetrieveData();
Cache.Insert("CrosswalkSPS", ds, null, DateTime.MaxValue, TimeSpan.FromMinutes(2));
lblCacheStatus.Text = "Created and added to cache.";
}
else
{
lblCacheStatus.Text = "Retrieved from cache.";
}
return ds;
}
// This method performs the database query, if the
// DataSet object isn't available in the cache.
private DataSet RetrieveData()
{
string connectionString = WebConfigurationManager.ConnectionStrings["dbbuddystring2"].ConnectionString;
string SQLSelect = "SELECT * FROM CrosswalkSPS";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(SQLSelect, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
adapter.Fill(ds, "CrosswalkSPS");
}
finally
{
con.Close();
}
return ds;
}
protected void cmdFilter_Click(object sender, EventArgs e)
{
DataSet ds = GetDataSet();
// Copy the DataSet so the cached item isn't affected
// when we remove columns.
ds = ds.Copy();
foreach (ListItem item in chkColumns.Items)
{
if (item.Selected)
{
ds.Tables[0].Columns.Remove(item.Text);
}
}
gridCustomers.DataSource = ds.Tables[0];
gridCustomers.DataBind();
}
}
答案 0 :(得分:0)