简体   繁体   English

从代码后面添加Gridview列的问题

[英]Issue with adding Gridview Columns from code behind

I have a gridview which displays some details about certain files. 我有一个gridview,显示有关某些文件的一些细节。 It has 5 columns including a template field which contains checkboxes. 它有5列,包括一个包含复选框的模板字段。

From the code behind, OnInit, I add a number of columns for additional information which may or may not be needed depending on the page. 从后面的代码OnInit中,我添加了许多列以获取可能需要或可能不需要的其他信息,具体取决于页面。 Code is below: 代码如下:

 for (int i = 0; i < models.Length && i < 3; i++)
            {
                var model = models[i];

                //Add gridview rows
                BoundField bf = new BoundField();
                bf.DataField = "Attribute" + i;
                bf.HeaderText = model.AttributeName;
                bf.Visible = true;

                gvFiles.Columns.Insert(6 + i, bf);

            }

This works well and I get the columns. 这很好用,我得到了列。 In the OnLoad event I databind certain data to the gridview and that works as well. 在OnLoad事件中,我将某些数据数据绑定到gridview,并且也可以。

The problem rises when a postback occurs. 发生回发时问题会增加。 Whenever the page creates a postback, it performs OnInit, then crashes with this ('on page') error message: 每当页面创建一个回发时,它执行OnInit,然后崩溃与此(“页面上”)错误消息:

An error has occurred because a control with id 'ctl00$MainContent$gvFiles$ctl02$ctl00' could not be located or a different control is assigned to the same ID after postback. 发生错误,因为无法找到ID为'ctl00 $ MainContent $ gvFiles $ ctl02 $ ctl00'的控件,或者在回发后为同一ID分配了不同的控件。 If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error. 如果未分配ID,请显式设置引发回发事件的控件的ID属性以避免此错误。

I identified the control which was giving the issue as the checkbox in the TemplateField, and I gave it an id. 我确定了将问题作为TemplateField中的复选框的控件,我给了它一个id。 However now, on postback the following happens: 但是现在,在回发时会发生以下情况:

  1. The checkbox in the TemplateFieldss don't appear TemplateFieldss中的复选框不会出现

  2. One of the columns is an ImageField and it loses its "Control-Style Width/Height" parameters and I get massive images. 其中一列是ImageField,它失去了“控制样式宽度/高度”参数,我得到了大量的图像。

The issue is only happening on postback, and removing the code which adds the columns pro grammatically makes everything work perfectly. 问题只发生在回发上,并且删除以编程方式添加列的代码使一切工作完美。

How can I get this to work ? 我怎样才能让它发挥作用?

Simply I tell the one line solution 我简单地告诉一线解决方案

You need to add !IsPostback in your Page Load event within your Gridview bind method 您需要在Gridview绑定方法中的Page Load事件中添加!IsPostback

Explain: 说明:

See the below code sample 请参阅以下代码示例

PageLoad()
{
BindGridview();
}

Public void BindGridview()
{
//Binding codes and add extra column codes
for (int i = 0; i < models.Length && i < 3; i++)
            {
                var model = models[i];

                //Add gridview rows
                BoundField bf = new BoundField();
                bf.DataField = "Attribute" + i;
                bf.HeaderText = model.AttributeName;
                bf.Visible = true;

                gvFiles.Columns.Insert(6 + i, bf);

            }
}

You have call the " BindGridview ()" method in page load .The same column field was created Whenever your page loaded. 您已在页面加载中调用“ BindGridview ()”方法。每当您的页面加载时,都会创建相同的列字段。

you need to call " BindGridview ()" method in page load at first time only.So you surly need !IsPostBack . 你需要在第一次只在页面加载中调用“ BindGridview ()”方法。所以你真的需要!IsPostBack

See this below code | 见下面的代码| or call this in inside of Page Init event 或者在Page Init事件内部调用它

PageLoad()
{
if(!IsPostBack)
{
BindGridview();
}
}

Now BindGridview(); 现在BindGridview(); method is called the page first time loading. 方法称为页面第一次加载。

More details about "IsPosteBack" property 有关“IsPosteBack”属性的更多详细信息

You need to re-create a dynamically added control on postback. 您需要在回发时重新创建动态添加的控件。

MSDN recommends creating controls in the PreInit event. MSDN建议在PreInit事件中创建控件。

Raised after the start stage is complete and before the initialization stage begins. 在启动阶段完成之后和初始化阶段开始之前引发。 Use this event for the following: 将此事件用于以下事项:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed. 检查IsPostBack属性以确定这是否是第一次处理页面。 The IsCallback and IsCrossPagePostBack properties have also been set at this time. 此时还设置了IsCallback和IsCrossPagePostBack属性。
  • Create or re-create dynamic controls. 创建或重新创建动态控件。
  • Set a master page dynamically. 动态设置母版页。
  • Set the Theme property dynamically. 动态设置Theme属性。
  • Read or set profile property values. 读取或设置配置文件属性值。

If there is an if(!ispostback) in your oninit event then remove it. 如果你的oninit事件中有if(!ispostback) ,那么将其删除。 The dynamic controls need to be created at every postback on the Oninit event only. 只需在Oninit事件的每个回发时创建动态控件。

If the control is not recreated then it can not be found, similar to what is happening in your case. 如果未重新创建控件,则无法找到它,类似于您的情况。 If the control is created say on PageLoad then the client side values would not be accessible and you will get a different error. 如果在PageLoad上创建控件,那么客户端值将无法访问,您将收到不同的错误。

Hope this helps. 希望这可以帮助。

The checkbox and the images are having problems cause the css failed due to errors. 复选框和图像出现问题导致css因错误而失败。 The error you are having is that when you do postback, there is already a row with the data you previously added, so to fix this you need the following code: 您遇到的错误是,当您进行回发时,已经有一行包含您之前添加的数据,因此要解决此问题,您需要以下代码:

protected void Page_Init(object sender, EventArgs e)
    {


        if (Page.IsPostBack)
        {
         gvFiles.DataBind();

        }

    }

If the number of columns you are adding on Post Back is different than the initial load, that could be the issue. 如果您在回发后添加的列数与初始加载不同,则可能是问题所在。 Specifically when the view state tries to load: 特别是当视图状态尝试加载时:

When adding a dynamic control c to some parent control p based on some condition (that is, when not loading them on each and every page visit), you need to make sure that you add c to the end of p's Controls collection. 根据某些条件(即,在每次访问时不加载它们时)将动态控件c添加到某个父控件p时,需要确保将c添加到p的Controls集合的末尾。 The reason is because the view state for p contains the view state for p's children as well, and, as we'll discuss in the "Parsing the View State" section, p's view state specifies the view state for its children by index . 原因是因为p的视图状态也包含p的子视图的状态,正如我们将在“解析视图状态”部分中讨论的那样,p的视图状态通过索引指定其子视图的状态 (Figure 5 illustrates how inserting a dynamic control somewhere other than the end of the Controls collection can cause a corrupted view state.) (图5说明了如何在Controls集合的末尾之外的某处插入动态控件可能会导致视图状态损坏。)

http://msdn.microsoft.com/en-us/library/ms972976.aspx http://msdn.microsoft.com/en-us/library/ms972976.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM