C#动态创建控件问题

发布于 2024-08-06 05:21:07 字数 1266 浏览 5 评论 0原文

我在从动态创建的下拉列表中检索值时遇到问题。所有控件均在 Page_Init 部分中创建。此时也会从列表项数组中添加列表项。 (控件的名称相同,因此应该可以访问视图状态以进行适当的设置。)

这是尝试检索值的函数:

protected void Eng98AssignmentComplete_Click(object sender, EventArgs e)
{
    String myID = "0";
    Page page = Page;
    Control postbackControlInstance = null;
    // handle the Button control postbacks
    for (int i = 0; i < page.Request.Form.Keys.Count; i++)
    {
        postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
        //Response.Write(page.Request.Form.Keys[i].ToString());
        if (postbackControlInstance is System.Web.UI.WebControls.Button)
        {
            myID = Convert.ToString(
                postbackControlInstance.ID.Replace("button_", ""));
        }
    }
    String txtholder = "ctl00$ContentPlaceHolder$Eng098Instructors_" + myID;
    Response.Write("MYID: " + myID + "<br/>");
    DropDownList ddInstructorCheck = (DropDownList)Page.FindControl(txtholder);
    Response.Write("Instructor Selected: "
      + ddInstructorCheck.SelectedValue + "<br/>");
}

这​​是我得到的输出,无论选择了哪个讲师......

MYID: 1_1
Instructor Selected: 0
ctl00$ContentPlaceHolder$Eng098Instructors_1_1

名称控件的正确性(通过查看源代码验证)...

想法?

i'm having issues retreiving the values out of a dynamically created dropdownlist. all controls are created in the Page_Init section. the listitems are added at that time as well from an array of listitems. (the controls are named the same so should be accessable to the viewstate for appropriate setting.)

here is the function that attempts to retrieve the values:

protected void Eng98AssignmentComplete_Click(object sender, EventArgs e)
{
    String myID = "0";
    Page page = Page;
    Control postbackControlInstance = null;
    // handle the Button control postbacks
    for (int i = 0; i < page.Request.Form.Keys.Count; i++)
    {
        postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
        //Response.Write(page.Request.Form.Keys[i].ToString());
        if (postbackControlInstance is System.Web.UI.WebControls.Button)
        {
            myID = Convert.ToString(
                postbackControlInstance.ID.Replace("button_", ""));
        }
    }
    String txtholder = "ctl00$ContentPlaceHolder$Eng098Instructors_" + myID;
    Response.Write("MYID: " + myID + "<br/>");
    DropDownList ddInstructorCheck = (DropDownList)Page.FindControl(txtholder);
    Response.Write("Instructor Selected: "
      + ddInstructorCheck.SelectedValue + "<br/>");
}

here is the output I get, no matter which instructor was selected.....

MYID: 1_1
Instructor Selected: 0
ctl00$ContentPlaceHolder$Eng098Instructors_1_1

the name of the control is correct (verified via view source)....

ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

記柔刀 2024-08-13 05:21:08

为什么不将控件保存在类的实例中,这样就不必使用 FindControl?

why not just save the control in an instance in your class so that you don't have to use FindControl?

司马昭之心 2024-08-13 05:21:08

您是否还在回发期间重新创建控件?动态生成/添加的控件必须根据每个请求重新创建,它们不会自动重新创建。

Do you also re-create the controls during the postback? Dynamically generated/added controls must be re-created with every request, they are not automatically re-created.

终陌 2024-08-13 05:21:08

为什么不把发件人投出去?这应该是导致回发的按钮:

string myId = "0";
Button btn = sender as Button;
if (btn != null)
    myId = btn.ID
...

Why don't you cast the sender? This should be the button that caused the postback:

string myId = "0";
Button btn = sender as Button;
if (btn != null)
    myId = btn.ID
...
鹿港巷口少年归 2024-08-13 05:21:08

您需要执行类似的操作,因为 UniqueID 属性是 Request.Form 中的关键。

        List<Button> buttons = new List<Button>();
        List<DropDownList> dropdowns = new List<DropDownList>();
        foreach (Control c in Controls)
        {
            Button b = (c as Button);
            if (b != null)
            {
                buttons.Add(b);
            }

            DropDownList d = (c as DropDownList);
            if (d != null)
            {
                dropdowns.Add(d);
            }
        }

        foreach (String key in Request.Form.Keys)
        {
            foreach (Button b in buttons)
            {
                if (b.UniqueID == key)
                {
                    String id = b.ID.Replace("button_", "");
                    String unique_id = "ctl00$ContentPlaceHolder$Eng098Instructors_" + id;
                    Response.Write("MYID: " + id + "<br/>");

                    foreach (DropDownList d in dropdowns)
                    {
                        if (d.UniqueID == unique_id)
                        {
                            Response.Write("Instructor Selected: " + d.SelectedValue + "<br/>");
                            break;
                        }
                    } 
                }
            }   
        }

You need to perform something like this because the UniqueID property is the key in Request.Form.

        List<Button> buttons = new List<Button>();
        List<DropDownList> dropdowns = new List<DropDownList>();
        foreach (Control c in Controls)
        {
            Button b = (c as Button);
            if (b != null)
            {
                buttons.Add(b);
            }

            DropDownList d = (c as DropDownList);
            if (d != null)
            {
                dropdowns.Add(d);
            }
        }

        foreach (String key in Request.Form.Keys)
        {
            foreach (Button b in buttons)
            {
                if (b.UniqueID == key)
                {
                    String id = b.ID.Replace("button_", "");
                    String unique_id = "ctl00$ContentPlaceHolder$Eng098Instructors_" + id;
                    Response.Write("MYID: " + id + "<br/>");

                    foreach (DropDownList d in dropdowns)
                    {
                        if (d.UniqueID == unique_id)
                        {
                            Response.Write("Instructor Selected: " + d.SelectedValue + "<br/>");
                            break;
                        }
                    } 
                }
            }   
        }
娜些时光,永不杰束 2024-08-13 05:21:08

我不确定为什么要在代码中生成控件(如果这样做,您仍然可以动态添加项目),但生成控件的代码可能会在这里提供巨大的帮助。我猜您没有设置列表项值,而只是设置列表项文本。尝试查看从 SelectedText 字段中获得的内容并发布您的控件创建函数。

编辑:
为了回应您对 @Martin 帖子的评论,您说“是的,每次创建页面(初始或回发)时,我都会在 Page_Init 函数中重新创建控件”。您在创建它们时是否也设置了选定的值?

即使您的数据来自数据库,您也可以在页面上使用控件,控件本身不必动态生成。

I'm not sure why you are generating the control in code (you can still add items dynamically if you do), but the code that generates the controls would probably be a huge help here. I'm guessing you are not setting the list item value, and instead just setting the list item text. Try seeing what you get from the SelectedText field and post your control creation function.

EDIT:
In response to your comment on @Martin's post, you said "yes I recreate the controls in the Page_Init function each time the page is created (initial or postback)". Are you also setting the selected value when you create them?

You can also use controls on the page even if your data comes from a database, the controls themselves don't have to be dynamically generated.

初雪 2024-08-13 05:21:08

这个怎么样?

((Button)sender).Parent.FindControl(myid)

编辑:我误解了你的问题。但我认为你应该遵循页面生命周期。这是动态创建的控件的常见问题。

我做了一些研究,这里有一些关于动态创建控件的信息可能会帮助你.. 。

How about this?

((Button)sender).Parent.FindControl(myid)

Edit:I misunderstood your question. But i think you should follow page lifecycle. it is common issue for dynamically created controls.

I did some research and here is some info about Dynamically Created Controls may help you...

毁梦 2024-08-13 05:21:08

我有 2 个渔获……这就是它们。

1.  I didn't clear the table I was adding to before re-creating the controls.

显然我昨天对细节的关注已经消失,我很确定控件的 ctlXX 领跑者在回发时由于我重新创建控件的方式而有一些不同的数字。

2.  I was assigning the same list to all the dropdownlist controls.  

一旦我将每次创建的查找称为下拉列表控件,一切都会正常工作。

无论如何,它的价值......

I had 2 catches.... here's what they were.

1.  I didn't clear the table I was adding to before re-creating the controls.

apparently my attention to detail was off yesterday, i'm pretty sure the ctlXX frontrunner of the control was some different number upon postback due to how I was recreating the controls.

2.  I was assigning the same list to all the dropdownlist controls.  

once I called the lookup upon each creation a dropdownlist control, all works well.

anyway for what it's worth....

通知家属抬走 2024-08-13 05:21:07

你需要做很多工作来构建这个奇特的字符串:

ctl00$ContentPlaceHolder$Eng098Instructors_1_1

这是控件的客户端 ID,而不是服务器 ID。该代码在服务器端运行,因此您需要服务器 ID。要使用服务器 ID 获取该控件,您需要执行以下操作:

ContentPlaceHolder.FindControl("Eng08Instructors_1_1");

注意,我没有查看页面,因为您的内容占位符创建了一个新的命名容器。

此外,循环设置 myID 变量的方式将始终最终保留 Keys 集合中的last 按钮。为什么还要费心循环呢?


根据您的评论,查找下拉列表 id 的更好方法如下:

string id = ((Control)sender).ID.Replace("button_", "Eng098Instructors_");

You're going to a lot of work to build this fancy string:

ctl00$ContentPlaceHolder$Eng098Instructors_1_1

That is the client ID of your control, not the server id. This code is running on the server side, and so you need the server id. To get that control using the server id, you need to do this:

ContentPlaceHolder.FindControl("Eng08Instructors_1_1");

Notice I didn't look in the page, because your content place holder created a new naming container.

Also, the way your loop is set up the myID variable will always end up holding the last button in the Keys collection. Why even bother with the loop?


Based on your comments, a better way to find the id of the dropdownlist is like this:

string id = ((Control)sender).ID.Replace("button_", "Eng098Instructors_");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文