Domanda

I'm trying to use a button in my gridview to pass the ID which is a GUID from my selected row to my database where I compare it with the guids in the database, I then pass it to my "Show" function and get the post from the database.

Right now I have no idea how to get the object "visadabok" from my button to my "Show".

protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {

            }
            else
            {
                //TextBox68.Text = Request["ID"];

                if (!string.IsNullOrEmpty(TextBox68.Text))
                {
                    Show(GridView1_RowCommand());
                }
            }
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Valj")
            {
                var valj = new Guid((string)e.CommandArgument);

                var visadagbok = (from x in DagbokFactoryBase.All
                                     where (x.ID == valj)
                                     select x).FirstOrDefault();
                return visadagbok;

            }

        }
<asp:TemplateField>
    <ItemTemplate>
    <asp:Button ID="AddButton" runat="server"
    CommandName="Valj"
    CommandArgument="<%# ((GridViewRow) Container).ID %>"
    Text="Gå till" />
    </ItemTemplate>
</asp:TemplateField>
È stato utile?

Soluzione

The return type for GridView1_RowCommand is void, hence the method won't be able to return any data to the Show method. There are 2 options which you can prefer to perform

  1. Call the Show method from the GridView1_RowCommand method (Best option as .net framework performs the event calling for the grid)

e.g.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
   if (e.CommandName == "Valj")
   {
        var valj = new Guid((string)e.CommandArgument);
        var visadagbok = (from x in DagbokFactoryBase.All
                                     where (x.ID == valj)
                                     select x).FirstOrDefault();
        Show(visadagbok);

   }
}
  1. If you want to write an event based programming for lose coupling, for this you will need to create an property which invokes a delegate when the property value is set. Assign value to the property from the "GridView1_RowCommand". This delegate would invoke the "Show" method.

like:

public delegate void ShowHandler(string id);

public string Id
{
    set
    {
        ShowHandler _show = new ShowHandler(Show);
        if (_show != null)
        {
            _show(value);
        }
    }
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    //set of existing code
    Id = visadagbok
}

public void Show(string Id)
{
    //set of code
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top