Pregunta

In my aspx page, I have,

<asp:ListView ID="listview1" runat="server" DataSourceID="dtasrc_load">

        <ItemTemplate>
            <h4>
                <asp:Label ID="lbl_titlename" runat="server" Text='<%#Eval("abt_vch_Title") %>'></asp:Label>
            </h4>
            <asp:LinkButton runat="server" OnClick="Content_Load" class="btn">Edit</asp:LinkButton>
            <asp:HiddenField ID="hiddenID" runat="server" Value='<%#Eval("abt_int_ID") %>' />
        </ItemTemplate>
    </asp:ListView>

I need to access the value in the hidden field control so that I can pass that value to the database on the linkbutton click event. Below is where I've gotten so far.

    protected void Content_Load(object sender, EventArgs e)
{

    HiddenField hd = new HiddenField();
    HiddenField myhiddenfield = new HiddenField();
    myhiddenfield = (HiddenField)listview1.FindControl("hiddenID");
    int myID = Convert.ToInt32(myhiddenfield.Value);

I get a run-time error as "Object not referenced to instance of an object". The value seems to be null.

Can anyone tell me why I am getting this? What should I do?

¿Fue útil?

Solución

give your linkbutton an id

<asp:LinkButton runat="server" OnClick="Content_Load" class="btn" 
id="editlinkbutton">Edit</asp:LinkButton>

and change your code to this

protected void Content_Load(object sender, EventArgs e)
{
    LinkButton editlinkbutton = sender as LinkButton;
    HiddenField myhiddenfield = editlinkbutton.NamingContainer.FindControl("hiddenID") as HiddenField;
    int myID = Convert.ToInt32(myhiddenfield.Value);
}

edit: maybe linkbutton doesnt have to have an id, not sure. my linkbuttons usually have id's :)

Otros consejos

I recently had a similar issue. Try not to look for System.Web.UI.WebControls.HiddenField, but rather for System.Web.UI.HtmlControls.HtmlInputHidden-class, here.

Additionally, you should be more cautious, rather use

System.Web.UI.HtmlControls.HtmlInputHidden hi =
listview1.FindControl("hiddenID") as ystem.Web.UI.HtmlControls.HtmlInputHidden;
if(hi != null)
...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top