Makishima
Makishima

Reputation: 125

Reading values in Gridview on Selection change of a DropDownList

I am really bad when it comes to playing with data inside a gridview. Here i have a simple gridview that contains a dropdownlist that gets its data from the database table Products.

enter image description here

what i want is on dropdownlist OnSelectedIndexChanged, the price label should read the price of the selected product in dropdownlist. the issue is when i select a product in dropdownlist the prices doesn't show. label remains empty.

ASP.NET

<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="true" PageSize="5" OnRowDataBound="Gridview1_RowDataBound">
  <Columns>
      <asp:BoundField DataField="RowNumber" HeaderText="#">
         <HeaderStyle CssClass="header" Width="60px"></HeaderStyle>
             </asp:BoundField>

      <asp:TemplateField HeaderText="Product">
             <ItemTemplate>
                  <asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
                  </asp:DropDownList>
              </ItemTemplate>
              <HeaderStyle CssClass="header" />
              <ItemStyle Width="170px" />
            </asp:TemplateField>


      <asp:TemplateField HeaderText="QTY">
            <ItemTemplate>
                 <asp:TextBox ID="qty_txtbox" runat="server" style="text-align:center;" OnTextChanged="TextBox2_TextChanged"></asp:TextBox>
            </ItemTemplate>
                  <ControlStyle Width="50px" CssClass="txt" />
                  <HeaderStyle CssClass="header" />
                  <ItemStyle Width="50px" CssClass="txt" />
            </asp:TemplateField>


      <asp:TemplateField HeaderText="Price (AED)">
           <ItemTemplate>
               <asp:Label ID="amount_lbl" runat="server"></asp:Label>
           </ItemTemplate>
               <HeaderStyle CssClass="header" />
               <ItemStyle Width="130px" CssClass="txt" />
               </asp:TemplateField>

        <asp:TemplateField HeaderText="">
            <ItemTemplate>
                <asp:ImageButton runat="server" ID="trash" Style="height: 20px;" ImageUrl="~/IMG/garbage.png" />
                </ItemTemplate>
                <ControlStyle Height="20px" Width="20px"></ControlStyle>
                <FooterStyle HorizontalAlign="center" />
                <HeaderStyle Height="30px" Width="30px" CssClass="header"></HeaderStyle>
                <FooterTemplate>
                     <asp:ImageButton runat="server" ID="addnew" ImageUrl="~/IMG/add.png" Style="height: 20px;" OnClick="ButtonAdd_Click" />
                </FooterTemplate>
            </asp:TemplateField>
    </Columns>

     <HeaderStyle CssClass="header" />
     <PagerStyle CssClass="pagerr" />
     <RowStyle CssClass="rows" />
 </asp:GridView>

Here is what i tried

private DataSet GetData()
{
    SqlCommand cmd = new SqlCommand("SELECT ProductName, PartNumber, price FROM Products");
    using (SqlConnection con = new SqlConnection(cDate.CS))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds);
                return ds;
            }
        }
}

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Find the DropDownList in the Row
        DropDownList ddproducts = (e.Row.FindControl("dropdown1") as DropDownList);
        ddproducts.DataSource = GetData();
        ddproducts.DataTextField = "ProductName";
        ddproducts.DataValueField = "ProductName";
        ddproducts.DataBind();

        //Add Default Item in the DropDownList
        ddproducts.Items.Insert(0, new ListItem("<----Please select---->"));

    }
}

protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
    string dvalue = Gridview1.SelectedRow.Cells[1].Text;
    string price = Gridview1.SelectedRow.Cells[3].Text;

    using (SqlConnection con = new SqlConnection(cDate.CS))
    {
        con.Open();
        SqlCommand myCommand = new SqlCommand("select price from products where ProductName = @name");
        myCommand.Parameters.AddWithValue("@name", dvalue);
        myCommand.Connection = con;

        using (SqlDataReader myReader = myCommand.ExecuteReader())
        {
            while (myReader.Read())
            {
                price = (myReader["price"].ToString());

            }
        }
    }
}

Error

Object reference not set to an instance of an object. for this line string dvalue = Gridview1.SelectedRow.Cells[1].Text;

Upvotes: 3

Views: 2520

Answers (2)

S.Serpooshan
S.Serpooshan

Reputation: 8388

It seems that you didn't set the price back to the grid!

Update: as mentioned by 'un-lucky', to get appropriate grid row we have use the dropdown which fires the event and get associated DataRow in its parents:

    protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var row = (sender as DropDownList).NamingContainer as GridViewRow; //instead of Gridview1.SelectedRow;
        string dvalue = row.Cells[1].Text; //or row.FindControl(id);
        //string price = row.Cells[3].Text;

        string price = "1400"; //get from database

        row.Cells[3].Text = price; //or row.FindControl(id);
        //Gridview1.new
    }

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29016

As the other answer stated, the issue main issues is you are not updating the result in that particular label. But that only solves your issues, you have do something more:

  • Identify the DataRow in which the control belongs to..
  • Get the label that you wanted to access.
  • Perform the operations
  • Assign the value back to the label.

The whole process can be implemented by using the following code, please take a look and let me know if you need any clarifications:

protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
   DropDownList ddlProduct = (DropDownList)sender;
   DataGridItem row = (DataGridItem) ddlProduct.NamingContainer;
   Label lblPrice = (Label)row.FindControl("amount_lbl");

   // Get current label Text
    string price = lblPrice.Text;
   // Perform your operations here

   // Assign the price value back to the label
   lblPrice.Text =  price;
}

Upvotes: 2

Related Questions