簡體   English   中英

如何在gridview中觸發LinkBut​​ton的點擊事件並在asp.net中顯示PopUp窗口

[英]How to fire click event of the LinkButton in gridview and Show PopUp window in asp.net

我試圖通過背后的代碼使用asp.net中的模板字段構建一個基於數據源的動態列gridview

為此,為了實現,我們開發了一個實現ITemplate接口的DynamicTemplate類。 在該模板字段中,我在每個單元格中插入了LinkButton ,當我單擊該單元格鏈接按鈕時,我需要顯示一個帶有選定單元格值的 Popup。

有關詳細示例,請從此鏈接下載

為此,我創建了一個 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顯示的數據很好。 這里的問題當我單擊 linkBut​​ton 時頁面重新加載並且在回發后沒有顯示網格

第二個問題是,對於LinkButtonClick Event沒有觸發

請向我提供幫助完整信息/示例,以在我們單擊 gridview 的 linkBut​​ton 時顯示模態窗口。

您需要使用 ajax 模型彈出擴展器。

使用您的字段設計一個面板並使用模型彈出窗口擴展器來顯示該彈出窗口

這個鏈接有它的樣本

www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/modalpopup/modalpopup.aspx

並在您的鏈接按鈕中單擊您必須使用 show 方法打開彈出窗口

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

    }

此代碼僅在它不是回發時才生成 gridview,但是當您單擊鏈接按鈕時會發生 postpack,這就是為什么單擊鏈接按鈕時 gridview 不會再次顯示的原因。

添加以下代碼(包含在 if 代碼中的其他 else 部分)以在單擊 lnkBut​​ton 時顯示 gridview

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();
                }
            }

        }

    }

CommandName屬性用於 Gridview 上的鏈接按鈕,並在代碼文件中為其指定一個特定名稱,然后在GridView 的 RowCommand 事件中准確使用它,這將是一個不錯的選擇,如下例所示:

首先是 .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();
            }

        }

我希望它對您的問題有所幫助,祝您快樂每一天:) !!

首先,您的 GridView 將在調用GenateGridView方法時創建,因此您每次回發時都必須調用此方法,那么您的 Page_Load 應該是

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

其次,我將向您展示另一種將 LinkBut​​ton 動態添加到 GridView 的方法。 我修改了你的GenateGridView只將標簽添加到DynamicTemplate ,還添加了這一行gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound); 處理添加LinkBut​​ton。

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事件處理程序中實現這樣的添加 LinkBut​​ton 並隱藏我們之前添加的標簽:

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);
        }
    }
}

您還可以將任何值設置為 LinkBut​​ton 的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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM