如何在www.example.com中触发网格视图中LinkButton的单击事件并显示弹出窗口asp.net

u7up0aaq  于 2022-12-24  发布在  .NET
关注(0)|答案(4)|浏览(141)

我已经尝试通过代码隐藏使用www.example.com中的模板字段构建一个基于数据源**的动态列网格视图asp.net。
为此,我们开发了一个类DynamicTemplate,它实现了ITemplate接口。在该模板字段中,我在每个单元格中插入了LinkButton,当我单击该单元格链接按钮时,我需要显示一个带有选定单元格值的弹出窗口。
For Detailed Sample Please download from this link
为此,我创建了一个Default.asxp页面,并编写了以下内容。

public partial class Default : System.Web.UI.Page
    {
        DataTable dt;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                GenateGridView();

        }

        private void GenateGridView()
        {
            TemplateField tempField;
            DynamicTemplate dynTempItem;
            LinkButton lnkButton;
            Label label;

            GridView gvDynamicArticle = new GridView();

            gvDynamicArticle.Width = Unit.Pixel(500);
            gvDynamicArticle.BorderWidth = Unit.Pixel(0);
            gvDynamicArticle.Caption = "<div>Default Grid</div>";
            gvDynamicArticle.AutoGenerateColumns = false;

            DataTable data = getBindingData();

            for (int i = 0; i < data.Columns.Count; i++)
            {
                tempField = new TemplateField();
                dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);

                lnkButton = new LinkButton();

                lnkButton.ID = string.Format("lnkButton{0}", i);
                lnkButton.Visible = true;

                string ColumnValue = data.Columns[i].ColumnName;
                tempField.HeaderText = ColumnValue;

                if (ColumnValue == "EmpName")
                {
                    label = new Label();

                    label.ID = string.Format("Label{0}", i);
                    dynTempItem.AddControl(label, "Text", ColumnValue);
                    label.Width = 100;
                }
                else
                {
                    dynTempItem.AddControl(lnkButton, "Text", ColumnValue);
                    lnkButton.Click += lnkButton_Click;
                }
                tempField.ItemTemplate = dynTempItem;
                gvDynamicArticle.Columns.Add(tempField);
                //////grdUserPivotDateTwo.Columns.Add(tempField);
            }

            gvDynamicArticle.DataSource = data;
            gvDynamicArticle.DataBind();

            divContainer.Controls.Add(gvDynamicArticle);

        }

        void lnkButton_Click(object sender, EventArgs e)
        {
            // showing cell values in popUp here.. 
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked')");
        }

        private DataTable getBindingData()
        {
            dt = new DataTable();
            dt.Columns.Add(new DataColumn("EmpName"));
            dt.Columns.Add(new DataColumn("Monday"));
            dt.Columns.Add(new DataColumn("TuesDay"));
            dt.Columns.Add(new DataColumn("WednesDay"));
            dt.Columns.Add(new DataColumn("ThursDay"));

            dt.Rows.Add("EmpOne", "p", "p", "p", "a");
            dt.Rows.Add("EmpTwo", "p", "a", "p", "p");
            dt.Rows.Add("EmpThree", "p", "p", "p", "a");
            dt.Rows.Add("EmpFour", "p", "a", "p", "p");
            dt.Rows.Add("EmpFive", "p", "p", "p", "a");
            dt.Rows.Add("EmpSix", "a", "p", "p", "p");

            return dt;

        }


    }

对应的DynamicTemplate类为

public class DynamicTemplate : System.Web.UI.ITemplate
{
    System.Web.UI.WebControls.ListItemType templateType;
    System.Collections.Hashtable htControls = new System.Collections.Hashtable();
    System.Collections.Hashtable htBindPropertiesNames = new System.Collections.Hashtable();
    System.Collections.Hashtable htBindExpression = new System.Collections.Hashtable();

    public DynamicTemplate(System.Web.UI.WebControls.ListItemType type)
    {
        templateType = type;
    }

    public void AddControl(WebControl wbControl, String BindPropertyName, String BindExpression)
    {
        htControls.Add(htControls.Count, wbControl);
        htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName);
        htBindExpression.Add(htBindExpression.Count, BindExpression);

    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        PlaceHolder ph = new PlaceHolder();

        for (int i = 0; i < htControls.Count; i++)
        {

            //clone control 
            Control cntrl = CloneControl((Control)htControls[i]);

            switch (templateType)
            {
                case ListItemType.Header:
                    break;
                case ListItemType.Item:
                    ph.Controls.Add(cntrl);
                    break;
                case ListItemType.AlternatingItem:
                    ph.Controls.Add(cntrl);
                    ph.DataBinding += new EventHandler(Item_DataBinding);
                    break;
                case ListItemType.Footer:
                    break;
            }
        }
        ph.DataBinding += new EventHandler(Item_DataBinding);

        container.Controls.Add(ph);

    }
    public void Item_DataBinding(object sender, System.EventArgs e)
    {
        PlaceHolder ph = (PlaceHolder)sender;
        GridViewRow ri = (GridViewRow)ph.NamingContainer;
        for (int i = 0; i < htControls.Count; i++)
        {
            if (htBindPropertiesNames[i].ToString().Length > 0)
            {
                Control tmpCtrl = (Control)htControls[i];
                String item1Value = (String)DataBinder.Eval(ri.DataItem, htBindExpression[i].ToString());
                Control ctrl = ph.FindControl(tmpCtrl.ID);

                Type t = ctrl.GetType();
                System.Reflection.PropertyInfo pi = t.GetProperty(htBindPropertiesNames[i].ToString());

                pi.SetValue(ctrl, item1Value.ToString(), null);
            }

        }


    }

    private Control CloneControl(System.Web.UI.Control src_ctl)
    {
        Type t = src_ctl.GetType();
        Object obj = Activator.CreateInstance(t);
        Control dst_ctl = (Control)obj;
        PropertyDescriptorCollection src_pdc = TypeDescriptor.GetProperties(src_ctl);
        PropertyDescriptorCollection dst_pdc = TypeDescriptor.GetProperties(dst_ctl);

        for (int i = 0; i < src_pdc.Count; i++)
        {

            if (src_pdc[i].Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
            {

                object collection_val = src_pdc[i].GetValue(src_ctl);
                if ((collection_val is IList) == true)
                {
                    foreach (object child in (IList)collection_val)
                    {
                        Control new_child = CloneControl(child as Control);
                        object dst_collection_val = dst_pdc[i].GetValue(dst_ctl);
                        ((IList)dst_collection_val).Add(new_child);
                    }
                }
            }
            else
            {
                dst_pdc[src_pdc[i].Name].SetValue(dst_ctl, src_pdc[i].GetValue(src_ctl));
            }
        }

        return dst_ctl;

    }
}

这里gridview中显示的数据很好。这里*问题*当我点击链接按钮时,页面重新加载,回发后没有网格显示
第二个问题是,对于**LinkButtonClick Event未启动**。
请向我提供帮助的完整信息/样本,以显示模态窗口时,我们点击链接按钮的网格视图。

yzxexxkh

yzxexxkh1#

你需要使用 AJAX 模型弹出扩展。
使用您的字段设计一个面板,并使用模型弹出窗口扩展器显示该弹出窗口
这个链接有它的样本
www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/modalpopup/modalpopup.aspx
在你的链接按钮点击你必须使用显示方法打开弹出窗口

qnakjoqk

qnakjoqk2#

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            GenateGridView();

    }

这段代码生成一个gridview只有当它不是一个postback,但是当你点击一个linkbutton一个postpack发生,这就是为什么gridview不再显示当你点击linkbutton.
添加以下代码(if代码中包含的其他else部分),以便在单击lnkButton时显示网格视图

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            GenateGridView();
        else
        {
            string ctrlName = Request.Params.Get("__EVENTTARGET").Trim();

            if (!String.IsNullOrEmpty(ctrlName))
            {
                if (ctrlName.StartsWith("lnkButton"))
                {
                    GenateGridView();
                }
            }

        }

    }
olqngx59

olqngx593#

最好在GridView上为linkbutton使用CommandName属性,并在代码文件中为其给予特定名称,然后在GridViewRowCommand事件中准确地使用它,如下例所示:

首先是.aspx文件:

<div>
        <asp:GridView ID="GridViewStudents" runat="server" AutoGenerateColumns="False" OnRowCommand="GridViewStudents_RowCommand">
            <Columns>
                <asp:TemplateField HeaderText="Stud_ID" Visible="False">
                    <ItemTemplate>
                        <asp:Label ID="LabelStudID" runat="server" Text='<%# Eval("Stud_ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="FKFather_ID" Visible="False">
                    <ItemTemplate>
                        <asp:Label ID="LabelFkFatherID" runat="server" Text='<%# Eval("Fk_Father_ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Student Name">
                    <ItemTemplate>
                        <asp:Label ID="LabelStudName" runat="server" Text='<%# Eval("Stud_Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Class Name">
                    <ItemTemplate>
                        <asp:Label ID="LabelRowlevelName" runat="server" Text='<%# Eval("Stud_Level_Row_Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:ImageButton ID="ImageButtonDelete" runat="server" CommandArgument='<%# Eval("Stud_ID") %>' CommandName="Remove" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

<div style="direction: ltr">
    <asp:Panel ID="Panel1" runat="server" Visible="false">
        <asp:Label ID="Labelpopupmessage" runat="server" Text=""></asp:Label>
        <br />
        <asp:Button ID="Buttonaccept" runat="server" Text="نعم" OnClick="Buttonaccept_Click" />
        <asp:Button ID="Buttoncancel" runat="server" Text="لا" OnClick="Buttoncancel_Click" />
    </asp:Panel>
    <asp:HiddenField ID="HiddenField1" runat="server" />
    <asp:ModalPopupExtender runat="server" ID="ModalPopupExtenderStudent" PopupControlID="ButtonSubmit" TargetControlID="HiddenField1" CancelControlID="Buttoncancel">
    </asp:ModalPopupExtender>
</div>

下面是我的示例的代码实现:

protected void GridViewStudents_RowCommand(object sender, GridViewCommandEventArgs e)
                {
                    if (e.CommandName == "Remove")
                    {
                       // I stored the ID of the selected Student I want to delete in a viewstate.
                                    ViewState.Add("DeletedStudDetailID",Convert.ToInt32(e.CommandArgument));
 ModalpopupExtender.Show();
                    }

                 }

// Here in the accept delete button I used that code ..
        protected void Buttonaccept_Click(object sender, EventArgs e)
        {
            try
            {
                if (ViewState["DeletedStudDetailID"] != null)
                {
                    StudentDetail StudDet = Data.StudentDetails.Single(SD => SD.Fk_Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
                    Data.StudentDetails.DeleteOnSubmit(StudDet);
                    Student Stud = Data.Students.Single(S => S.Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
                    Data.Students.DeleteOnSubmit(Stud);
                    Data.SubmitChanges();
                }
                this.ResultMessage = "Delete Done Sucessfully !!";
            }
            catch
            {
                this.ErrorMessage = "Delete operation disordered !!";
            }
            finally
            {
                ModalPopExtender.Hide();
            }

        }

我希望这对你的问题有帮助,祝你有快乐的一天:)!!

oaxa6hgo

oaxa6hgo4#

首先,在调用GenateGridView方法时将创建GridView,因此每次回发时都必须调用此方法,然后Page_Load应为

protected void Page_Load(object sender, EventArgs e)
{
   GenateGridView();
}

其次,我将向您展示动态添加LinkButton到GridView的另一种方法。我修改了您的GenateGridView,以便仅将标签添加到DynamicTemplate中,还添加了此行**gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound);**以处理添加LinkButton。

private void GenateGridView()
{
    TemplateField tempField;
    DynamicTemplate dynTempItem;
    Label label;

    GridView gvDynamicArticle = new GridView();

    gvDynamicArticle.Width = Unit.Pixel(500);
    gvDynamicArticle.BorderWidth = Unit.Pixel(0);
    gvDynamicArticle.Caption = "<div>Default Grid</div>";
    gvDynamicArticle.AutoGenerateColumns = false;
    gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound);
    DataTable data = getBindingData();

    for (int i = 0; i < data.Columns.Count; i++)
    {
        tempField = new TemplateField();
        dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);

        string ColumnValue = data.Columns[i].ColumnName;
        tempField.HeaderText = ColumnValue;

        label = new Label();

        label.ID = string.Format("Label{0}", i);
        dynTempItem.AddControl(label, "Text", ColumnValue);
        label.Width = 100;

        tempField.ItemTemplate = dynTempItem;
        gvDynamicArticle.Columns.Add(tempField);
    }

    gvDynamicArticle.DataSource = data;
    gvDynamicArticle.DataBind();

    divContainer.Controls.Add(gvDynamicArticle);
}

我在GridView的RowDataBound事件处理程序中这样实现,以添加LinkButton并隐藏之前添加的Label:

protected void gvDynamicArticle_RowDataBound(object sender, GridViewRowEventArgs e) 
{
    for (int j = 1; j < e.Row.Cells.Count; j++)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lnkButton = new LinkButton();
            lnkButton.ID = string.Format("lnkButton{0}{1}", e.Row.DataItemIndex, j);
            lnkButton.Click += new EventHandler(lnkButton_Click);

            Label tempLabel = e.Row.FindControl("Label" + j) as Label;
            lnkButton.Text = tempLabel.Text;
            lnkButton.CommandArgument = tempLabel.Text;

            tempLabel.Visible = false;

            e.Row.Cells[j].Controls.Add(lnkButton);
        }
    }
}

您还可以将任何值设置为LinkButton的CommandArgument,然后可以在警报中显示它。
最后,看起来你想在警报中显示一些值,你可以这样编码

public void lnkButton_Click(object sender, EventArgs e)
{
    // showing cell values in popUp here.. 
    LinkButton lnk = (LinkButton)sender;
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked, value " + lnk.CommandArgument + "')", true);
}

相关问题