简体   繁体   中英

Populates GridView2 based on selected row from GridView1

I have 2 gridview on my page: on GridView1 I have a column with select link, Id and Name which looks like this:

Select | Id | Name
select | 101 | Jack
select | 102 | Cath

Now, what I am trying to do is let's say, I clicked the select from the first row which is Jack, now my GridView2 will display the products ordered by Jack which looks like this:

Id | ProductID
101 | 111
101 | 222
101 | 333

and if Cath whom I selected, GridView2 will change the display products which ordered by Cath:

Id | productID
102 | 111
102 | 333
102 | 555

In short, I am trying to populate GridView2 based on the selected row from the GridView1. I am using asp.net with C#.

When you are selecting the row in 1st grid then in selectIndexChanged event of your grid take the value of the primary key ID and store in hiddenField If you have used Datakey then use

 SelectedDatakey

take the value of SelectedDatakey and store in hiddenfield

protected void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
  {

   hiddenfield1.value = CustomersGridView.SelectedDataKey.Value;

  }

Now In your query to fill the 2nd grid pass the 1st grid's key value which you have stored in hiddenfield in where condition and populate the second grid according to your query result

This is my sample code......

  protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<Data> DataList = new List<Data>() { new Data { id = 1, id2 = 2 }, new Data { id = 3, id2 = 4 } };
        GridView1.DataSource = DataList;
        GridView1.DataBind();
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    GridViewRow row = (GridViewRow ) btn.NamingContainer;

    Label slNoLabel = (Label) row.FindControl("slNoLabel");
    // function to get data based on label vlue
    GridView2.DataSource=GetData(slNoLabel.Text);
    GridView2.DataBind();

}

DataTable GetData(string value)
{
DataTable tbl = new DataTable ();
    //   Calling DB 
    return tbl;
    }
}

public class Data
{
    public int id { get; set; }
    public int id2 { get; set; }
}

and in the UI

 <div>
    <asp:GridView ID="GridView1" runat="server">
        <Columns>
            <asp:TemplateField ShowHeader="False">
                <ItemTemplate>
                    <asp:Button ID="Button1" runat="server" CausesValidation="False" CommandName="Select" OnClick="Button1_Click" Text="Select" />
                    <asp:Button ID="Button2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:GridView ID="GridView2" runat="server"></asp:GridView>
</div>

You can add an onClick method on the link button you added for "Select".

   <asp:GridView ID="Gridview1" runat="server"
                    AllowPaging="true" PageSize="15" RowStyle-Wrap="true" EmptyDataRowStyle-ForeColor="Red"
                    AutoGenerateColumns="false" GridLines="None">
                    <Columns>
                        <asp:TemplateField HeaderText="Select">
                            <ItemTemplate>
                            <asp:LinkButton ID ="li_Select" runat="server" Text="Select" OnClick="li_Select_Click"></asp:LinkButton>                                   
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="ID">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="lbl_ID" Text='<%#Eval("ID") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label runat="server" ID="lbl_Name" Text='<%#Eval("Name") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>

                </asp:GridView>                  

Now Filter the data or fetch the data from the database on the basis of clicked row ID.

  protected void li_Select_Click(object sender, EventArgs e)
{

    LinkButton lnkbtn = (LinkButton)sender;
    GridViewRow row = (GridViewRow)lnkbtn.NamingContainer;
    Label lbl_ID = (Label)row.FindControl("lbl_ID");

  // You can fetch the data from the database on the basis of selected User ID .
    DataTable dt = new DataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Product_ID");
    for (int i = 100; i <= 110; i++)
    {
        DataRow dr = dt.NewRow();
        dr["ID"] = i;
        dr["Product_ID"] = "P_" + i;
        dt.Rows.Add(dr);
    }
    // In this method you pass the id of the user, and datatable fetched from the    database of all products. or you can pass the id in the storedprocedure to get data of selected user only and then bind it here .
    GetData(lbl_ID.Text,dt);
}
protected void GetData(string ID, DataTable dt)
{       

    DataView dv = dt.DefaultView;
    dv.RowFilter = "ID=" + ID;
    Gridview2.DataSource = dv;
    Gridview2.DataBind();

}

The best way of doing this in my opinion is to use UpdatePanel to bind the second grid, using this you will have an advantage, no postback (it is postback actually, but the user wont notice it..)...

And if you don't use the UpdatePanel , then there is no way you can see the data after binding it in the postback (unless you are doing it through Javascript, which is a hassle)...Here is the sample code for achieving it:

ASPX Page:

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:GridView ID="GridView2" runat="server" >
            <Columns>

            </Columns>
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

<asp:UpdatePanel runat="server">
    <ContentTemplate>
    <asp:GridView ID="GridView1" runat="server">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:LinkButton ID="asd" Text='Select' runat="server" OnClick="link_click"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

Code Behind:

protected override void PageLoad(object sender, System.EventArgs e)
{

    if (!IsPostBack)
    {

        GridView1.DataSource = getDataSource();
        GridView1.DataBind();

    }
}
private DataTable getDataSource()
{

    SqlConnection conn = new SqlConnection("Server=192.168.1.1;DATABASE=dummy;UID=****;PWD=*****;");    //Example connString
    SqlCommand comm = new SqlCommand("SELECT * FROM Table1", conn);
    SqlDataAdapter ad = new SqlDataAdapter(comm);

    DataTable ta = new DataTable();
    ad.Fill(ta);

    return ta;
}

protected void button_click(object sender, EventArgs e)
{
    LinkButton asd = (LinkButton)sender;
    GridViewRow row = (GridViewRow)asd.NamingContainer;     //Gets the selected Row

    string user_id = row.Cells[2].Text;     //Use this to get any value you want.
    //Can now use the user_name to get the data for the grid 2, and update the panel
    GridView2.DataSource = getDataSource2(user_id);
    GridView2.DataBind();
    UpdatePanel1.Update();
}
private DataTable getDataSource2(string user_id)
{
    string sql = "SELECT * FROM TABLE2 WHERE user_id = @user_id";
    SqlConnection conn = new SqlConnection("Server=sqlserver\\sql2008;DATABASE=esm80;UID=sa;PWD=sa;");    //Example connString
    SqlCommand comm = new SqlCommand();
    comm.CommandText = sql;
    comm.Parameters.AddWithValue("@name", user_id);
    comm.Connection = conn;

    SqlDataAdapter ad = new SqlDataAdapter(comm);

    DataTable ta = new DataTable();
    ad.Fill(ta);

    return ta;
}

Now the explaination, the UpdatePanel of GridView2 is there to update the gridView2 once the data is binded to it (this will show the newly binded data). The UpdatePanel of GridView1 is there to prevent the postback, from the link button.

Hope this answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM