查找动态创建的控件时出错



我使用Fileupload控件上传图像,加载文件后,当我单击"上传"按钮时,文件将保存在服务器中的文件夹中,但在保存到数据库之前,我需要在图像的同时添加图像描述。。但我不知道我犯了一些错误。我可以将文件保存在文件夹中,但当我将其保存到数据库中时,只会找到一个动态添加的控件,然后它会提供对象引用,而不是设置为对象的实例即使在特定的div中有多个控件。在进入代码之前,我会在上传文件后告诉我要添加哪些控件。。我正在为我上传的每个图像文件添加一个图像控件和文本框。。当我只上传一个文件时,它会在第一次上传后再次进入foreach循环。。我的代码可能会解释得更多。

这是我的.aspx代码:

<form id="ContentPlaceHolder1" runat="server">
    <div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
      <asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/>
        <asp:Button runat="server" ID="uploadedFile" style="position:absolute;  font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" />
        <asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">
             <asp:Button ID="btnsave" runat="server" UseSubmitBehavior="true" Text="Save" OnClick="btnsave_Click" Font-Bold="true" BackColor="Yellow"></asp:Button>
        </asp:Panel>
     </div>

    </form>

这是我的后端代码。

SqlCommand com = new SqlCommand();
SqlConnection con = new SqlConnection();
SqlDataReader reader;
int id = 0;
StringBuilder sb = new StringBuilder();
string filepath = "";
string newpath = "";
int tid = 0;
int count = 0;
int cnt1 = 0;
string textid = "";
Panel dload;
Image img;
TextBox ta;
protected void Page_Load(object sender, EventArgs e)
{
    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    con.Open();
    com = new SqlCommand("select max(slid) from slider", con);
    reader = com.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            id = Convert.ToInt32(reader.GetInt32(0));
        }
    }
    con.Close();
    com.Dispose();
    HtmlGenericControl dh = new HtmlGenericControl("div");
    dh.Attributes.Add("class", "head");
    dh.InnerText = "Write Description";
    updtpanel.Controls.Add(dh);
    foreach (HttpPostedFile upld in UploadImages.PostedFiles)
    {
        createImgPanel();
    }
}

protected void uploadFile_Click(object sender, EventArgs e)
{
    if (UploadImages.HasFiles)
    {
       string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
       if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
       {
           foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
           {
               count += 1;
               filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
               uploadedFile.SaveAs(filepath);
               newpath = "../Images/Gallery/" + uploadedFile.FileName;
               try
               {
                   Image nimg = dload.FindControl("img" + count) as Image;
                   nimg.ImageUrl = newpath.ToString();
               }
               catch (Exception ex)
               {
                   Response.Write(ex.Message);
               }
           }
       }
       else
       {
           Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
       }
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);        
    }
}
public void createImgPanel()
{
    tid = tid + 1;
    textid = "txt" + tid;
    ta = new TextBox();
    img = new Image();
    ta.TextMode = TextBoxMode.MultiLine;
    dload = new Panel();
    updtpanel.Visible = true;
    dload.Attributes.Add("class", "dataload");
    //dload.Attributes.Add("runat", "server");
    dload.ID = "ind" + tid;
    img.CssClass = "loadimg";
    img.ID = "img" + tid;
    //img.Attributes.Add("runat", "server");
    ta.Attributes.Add("class", "txtdes");
    ta.ID = textid;
    //ta.Attributes.Add("runat", "server");
    dload.Controls.Add(img);
    dload.Controls.Add(ta);
    updtpanel.Controls.Add(dload);
}
protected void btnsave_Click(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
            Panel pv = (this.Form.FindControl("mainbk").FindControl("updtpanel")) as Panel;
            foreach (Control cd in pv.Controls)
            {
                cnt1 = cnt1 + 1;
                TextBox txt = cd.FindControl("ind" + cnt1).FindControl("txt" + cnt1) as TextBox;****This is where I am getting the above said error****
                Image img = cd.FindControl("ind" + cnt1).FindControl("img" + cnt1) as Image;
                    string str = "";
                    str = txt.Text;
                    string iurl = "";
                    iurl = img.ImageUrl;
                    id += 1;
                    string Insert = "Insert into slider (slid,slurl,slalt) values (@id,@IMAGE_PATH,@alter)";
                    SqlCommand cmd = new SqlCommand(Insert, con);
                    cmd.Parameters.AddWithValue("@IMAGE_PATH", iurl);
                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.Parameters.AddWithValue("@alter", str);
                    try
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    catch (Exception e1)
                    {
                        Response.Write(e1.Message);
                    }
                }


        updtpanel.Visible = false;
    }
}

*我在上面代码的最后一部分遇到错误,即保存按钮点击事件。对于"文本框查找"控件,我遇到错误。第一个图像将被成功保存,但对于其他图像,即使它们存在于设计中,它也无法找到控制*

我只想知道我是否在保存点击事件中犯了任何错误,或者整个编码本身是否有任何错误

编辑

因此,这是在运行时呈现控件后的HTML源代码:

    <div id="mainbk" class="transbox" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;">
          <input type="file" multiple="multiple" name="UploadImages" id="UploadImages" style="width:500px;background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;">
            <input type="submit" name="uploadedFile" value="Upload" id="uploadedFile" style="position:absolute;  font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;">
            <div id="updtpanel" class="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute">
                 <input type="submit" name="btnsave" value="Save" id="btnsave" style="background-color:Yellow;font-weight:bold;">
            <div class="head">Write Description</div><div id="ind1" class="dataload">
            <img id="img1" class="loadimg" runat="server" src="../Images/Gallery/God%201.jpg">
<textarea name="txt1" rows="2" cols="20" id="txt1" class="txtdes"></textarea>
        </div><div id="ind2" class="dataload">
            <img id="img2" class="loadimg" runat="server" src="../Images/Gallery/God%202.jpg">
<textarea name="txt2" rows="2" cols="20" id="txt2" class="txtdes"></textarea>
        </div><div id="ind3" class="dataload">
            <img id="img3" class="loadimg" runat="server" src="../Images/Gallery/God%203.jpg">
<textarea name="txt3" rows="2" cols="20" id="txt3" class="txtdes"></textarea>
        </div>
    </div>
         </div>

已编辑

K我只是更深入地了解了我遇到的异常。。。据说。。

'((System.Web.UI.HtmlControls.HtmlContainerControl)(dv)).InerHtml'引发了类型为"System.Web.HttpException"的异常

这到底意味着什么。。它还说控制不是字面意义上的。。那是什么意思。。为什么找不到我附加的控件请帮帮我。。

在PreRender事件中添加控件,至少从PageLoad访问它们。

在HTML源代码被渲染到浏览器后,您还可以包括它吗?如果cd.FindControl("ind" + cnt1)在第一种情况下返回null怎么办?

cd.FindControl("ind" + cnt1).FindControl("txt" + cnt1) as TextBox

最新更新