添加动态列一个ASP.NET的GridView [英] Adding dynamic columns to an ASP.NET Gridview

查看:152
本文介绍了添加动态列一个ASP.NET的GridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,动态地添加列到GridView。我需要改变布局 - 即包含列 - 基于在DropDownList中的值。当用户在此列表中改变选择,我需要根据选择以除去所有未在第一列和动态地添加额外的列

I'm having a problem dynamically adding columns to a GridView. I need to change the layout -- i.e. the included columns -- based on the value in a DropDownList. When the user changes the selection in this list, I need to remove all but the first column and dynamically add additional columns based on the selection.

我在我的标记定义只有一个列 - 列0,一个模板列,在我宣布选择链接和其他应用程序的具体LinkBut​​ton的。这列需要永远存在。当ListBoxSelection制成,我删除所有,但第一列,然后重新添加所需的列(在此示例中,我已经简化它总是添加一个标题栏)。这里是code的一部分:

I have only one column defined in my markup -- column 0, a template column, in which I declare a Select link and another application specific LinkButton. That column needs to always be there. When the ListBoxSelection is made, I remove all but the first column and then re-add the desired columns (in this sample, I've simplified it to always add a "Title" column). Here is a portion of the code:

RemoveVariableColumnsFromGrid();
BoundField b = new BoundField();
b.DataField = "Title";
this.gvPrimaryListView.Columns.Add(b);
this.gvPrimaryListView.DataBind();


private void RemoveVariableColumnsFromGrid() {
    int ColCount = this.gvPrimaryListView.Columns.Count;
    //Leave column 0 -- our select and view template column
    while (ColCount > 1) {
        this.gvPrimaryListView.Columns.RemoveAt(ColCount - 1);
        --ColCount;
    }
}

第一次这样code贯穿而过,我看到两个静态列和动态添加职称一栏。然而,一个选择是由下一个时间,第一列中产生空的(在它没有)。我看到标题列,我看到的第一列在​​它的左边 - 但是有在它产生什么。在调试器,我可以看到,gvPrimaryListView确实仍然有两列和第一个(索引0)的确是一个模板列。事实上,柱甚至保留它的将在下面的标记设定为165像素(用于调试目的)宽度

The first time this code runs through, I see both the static column and the dynamically added "Title" column. However, the next time a selection is made, the first column is generated empty (nothing in it). I see the title column, and I see the first column to its left -- but there's nothing generated within it. In the debugger, I can see that gvPrimaryListView does indeed still have two columns and the first one (index 0) is indeed a template column. In fact, the column even retains it's width which is set as 165px in the markup below (for debugging purposes).

任何想法?

<asp:GridView ID="gvPrimaryListView" runat="server" Width="100%" AutoGenerateColumns="false"
    DataKeyNames="Document_ID" EnableViewState="true" DataSourceID="odsPrimaryDataSource"
    AllowPaging="true" AllowSorting="true" PageSize="10" OnPageIndexChanging="activeListView_PageIndexChanging"
    AutoGenerateSelectButton="False" OnSelectedIndexChanged="activeListView_SelectedIndexChanged"
    Visible="true" OnRowDataBound="CtlDocList_RowDataBound" Font-Size="8pt" Font-Names="Helvetica">
    <Columns>
        <asp:TemplateField ShowHeader="false">
            <ItemTemplate>
                <asp:LinkButton EnableTheming="false" ID="CtlSelectDocRowBtn" runat="server" Text="Select"
                    CommandName="Select" CssClass="gridbutton" OnClick="RowSelectBtn_Click" />
                <asp:ImageButton EnableTheming="false" ID="DocViewBtn" runat="server" ImageUrl="../../images/ViewDoc3.png"
                    CssClass="gridbutton" CommandName="Select" OnClick="DocViewBtn_Click" />
            </ItemTemplate>
            <ItemStyle Width="165px" />
        </asp:TemplateField>
    </Columns>
    <EmptyDataTemplate>
        <asp:Label ID="Label6" runat="server" Text="No rows found." SkinID="LabelHeader"></asp:Label>
    </EmptyDataTemplate>
</asp:GridView>


只是一些额外的信息。


Just some additional information.

它无关的事实,这是第一列,但一切都做的事实,这是一个TemplateField。如果我把一个正常的列向左(在标记)和模板列列向右移,第一列呈现罚款和(现二)模板列列消失。

It has nothing to do with the fact that it is the first column but everything to do with the fact that it is a TemplateField. If I put a normal column to the left (in the markup) and shift the TemplateField column to the right, the first column renders fine, and the (now second) TemplateField column disappears.

另一个奇怪的事情 - 这个问题不会发生第一回发 - 或第二 - 但它开始在第三回发,然后继续进行后续的回传。我难倒。

Another strange thing -- the problem doesn't happen the first postback -- OR THE SECOND -- but it starts on the third postback and then continues for subsequent postbacks. I'm stumped.

推荐答案

最近,我征服了,在GridView的动态列silmilar问题,这或许会有所帮助。

I recently conquered silmilar issues with dynamic columns in gridviews, perhaps this will help.

首先将视图状态关闭结果
其次编程添加列在OnInit事件发射功能结果
最后我用下面的辅助类造成的复选框实例时RowDataBound事件拉开序幕。有一些很难codeD。

First turn the viewstate off
Second add the columns programatically in a function fired in the oninit event
Lastly I used the following helper class to cause the checkboxes to instantiate when the RowDataBound event kicked off. Yes some of it is hard coded.

这里到底是所有code。有它:)作为信息披的是,等等等等...

Heck here is all the code. Have at it :) Warrenty as is, blah blah blah...

最后,因为我刚开始我的脚湿DOTNET的任何提示会pciated AP $ P $ [IE不宰我太多:)。是的借的初始$ C $从带C的地方,对不起,我不记得了我的头顶:(

Finally since I am just getting my feet wet DotNet any tips would be appreciated [IE don't rip me too much :) ]. And yes 'borrowed' the initial code from the web somewhere, sorry I cant remember off the top of my head :(

- 消防这一关在保护覆盖无效的OnInit

-- Fire this off in protected override void OnInit

	private void GridViewProject_AddColumns()
	{
		DataSet dsDataSet = new DataSet();
		TemplateField templateField = null;

		try
		{
			StoredProcedure sp = new StoredProcedure("ExpenseReportItemType_GetList", "INTRANETWEBDB", Context.User.Identity.Name);
			dsDataSet = sp.GetDataSet();

			if (sp.RC != 0 && sp.RC != 3000)
			{
				labelMessage.Text = sp.ErrorMessage;
			}

			int iIndex = 0;
			int iCount = dsDataSet.Tables[0].Rows.Count;
			string strCategoryID = "";
			string strCategoryName = "";
			iStaticColumnCount = GridViewProject.Columns.Count;

			// Insert all columns immediatly to the left of the LAST column
			while (iIndex < iCount)
			{
				strCategoryName = dsDataSet.Tables[0].Rows[iIndex]["CategoryName"].ToString();
				strCategoryID = dsDataSet.Tables[0].Rows[iIndex]["CategoryID"].ToString();

				templateField = new TemplateField();
				templateField.HeaderTemplate = new GridViewTemplateExternal(DataControlRowType.Header, strCategoryName, strCategoryID);
				templateField.ItemTemplate = new GridViewTemplateExternal(DataControlRowType.DataRow, strCategoryName, strCategoryID);
				templateField.FooterTemplate = new GridViewTemplateExternal(DataControlRowType.Footer, strCategoryName, strCategoryID);

				// Have to decriment iStaticColumnCount to insert dynamic columns BEFORE the edit row
				GridViewProject.Columns.Insert((iIndex + (iStaticColumnCount-1)), templateField);
				iIndex++;
			}
			iFinalColumnCount = GridViewProject.Columns.Count;
			iERPEditColumnIndex = (iFinalColumnCount - 1); // iIndex is zero based, Count is not
		}
		catch (Exception exception)
		{
			labelMessage.Text = exception.Message;
		}
	}

- 助手类

public class GridViewTemplateExternal : System.Web.UI.ITemplate
{
	#region Fields
	public DataControlRowType DataRowType;
	private string strCategoryID;
	private string strColumnName;
	#endregion

	#region Constructor
	public GridViewTemplateExternal(DataControlRowType type, string ColumnName, string CategoryID)
	{
		DataRowType = type; // Header, DataRow,
		strColumnName = ColumnName; // Header name
		strCategoryID = CategoryID;
	}
	#endregion

	#region Methods
	public void InstantiateIn(System.Web.UI.Control container)
	{
		switch (DataRowType)
		{
			case DataControlRowType.Header:
				// build the header for this column
				Label labelHeader = new Label();
				labelHeader.Text = "<b>" + strColumnName + "</b>";
				// All CheckBoxes "Look Up" to the header row for this information
				labelHeader.Attributes["ERICategoryID"] = strCategoryID;
				labelHeader.Style["writing-mode"] = "tb-rl";
				labelHeader.Style["filter"] = "flipv fliph";
				container.Controls.Add(labelHeader);
				break;
			case DataControlRowType.DataRow:
				CheckBox checkboxAllowedRow = new CheckBox();
				checkboxAllowedRow.Enabled = false;
				checkboxAllowedRow.DataBinding += new EventHandler(this.CheckBox_DataBinding);
				container.Controls.Add(checkboxAllowedRow);
				break;
			case DataControlRowType.Footer:
				// No data handling for the footer addition row
				CheckBox checkboxAllowedFooter = new CheckBox();
				container.Controls.Add(checkboxAllowedFooter);
				break;
			default:
				break;
		}
	}
	public void CheckBox_DataBinding(Object sender, EventArgs e)
	{
		CheckBox checkboxAllowed = (CheckBox)sender;// get the control that raised this event
		GridViewRow row = (GridViewRow)checkboxAllowed.NamingContainer;// get the containing row
		string RawValue = DataBinder.Eval(row.DataItem, strColumnName).ToString();
		if (RawValue.ToUpper() == "TRUE")
		{
			checkboxAllowed.Checked = true;
		}
		else
		{
			checkboxAllowed.Checked = false;
		}
	}
	#endregion
}

这篇关于添加动态列一个ASP.NET的GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆