3

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;

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Makishima
  • 125
  • 13

2 Answers2

2

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
    }
S.Serpooshan
  • 7,608
  • 4
  • 33
  • 61
  • i am getting an error `Object reference not set to an instance of an object.` for `string dvalue = Gridview1.SelectedRow.Cells[1].Text;` – Makishima Jan 19 '17 at 07:28
  • @Makishima: Probably this will be another question, and are explained [here](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – sujith karivelil Jan 19 '17 at 07:30
  • @un-lucky i understand it means that the value is null. am i not getting the gridview cell value right ? – Makishima Jan 19 '17 at 07:33
  • You can get the value in this way: `GridViewRow row = Gridview1.Rows[e.NewSelectedIndex];`.. `string dvalue = row.Cells[1].Text;` @Makishima – Null Jan 19 '17 at 07:35
  • so it is another problem: the `Gridview1.SelectedRow` is probably null at the time of `dropdown1_SelectedIndexChanged`. we have to get that row in other way... – S.Serpooshan Jan 19 '17 at 07:43
  • @Makishima: You cant directly access the values like this, you should get the label first and then update the value, I have added an answer, please take a look – sujith karivelil Jan 19 '17 at 07:45
2

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;
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88