Home > Enterprise >  Gridview.SelectedRow returns null
Gridview.SelectedRow returns null

Time:01-18

This is my code for displaying the gridview:

protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                LoadCart();
            }

        }
        protected void LoadCart()
        {
            string _connStr = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
            SqlConnection SQLConn = new SqlConnection(_connStr);
            SqlDataAdapter SQLAdapter = new SqlDataAdapter("SELECT M.menuItemName, M.menuItemImage,totalQuantity, M.menuItemPrice * totalQuantity Total_Price"  
                " FROM Cart C INNER JOIN itemSelected I ON C.username   C.itemSelectedID = I.username   I.itemSelectedID"  
                " INNER JOIN menuItem M ON I.menuItemID   I.stallID = M.menuItemID   M.stallID", SQLConn);
            
            DataTable DT = new DataTable();
            SQLAdapter.Fill(DT);
            CartGridView.DataSource = DT;
            CartGridView.DataBind();
            LoadPrice();
        }
        protected void LoadPrice()
        {
            string _connStr = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
            SqlConnection SQLConn = new SqlConnection(_connStr);
            SqlCommand cmd = new SqlCommand("SELECT SUM(M.menuItemPrice * totalQuantity)tabulatedPrice"  
                " FROM Cart C INNER JOIN itemSelected I ON C.username   C.itemSelectedID = I.username   I.itemSelectedID"  
                " INNER JOIN menuItem M ON I.menuItemID   I.stallID = M.menuItemID   M.stallID", SQLConn);
            SQLConn.Open();
            lbl_TotalPrice.Text = cmd.ExecuteScalar().ToString(); 
            SQLConn.Close();
        }

This is my code in attempting to retrieve a specific row, but it returns null.

protected void CartGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int result = 0;
            Cart cart = new Cart();
            GridViewRow row = CartGridView.SelectedRow;
            string itemName = row.Cells[0].Text;
            if (e.CommandName == "minusQuantity")
            {
                int quantity = int.Parse(row.Cells[3].Text) - 1;
                if (quantity > 0)
                {
                    cart.CartUpdateQuantity(quantity, itemName);
                }
                else
                {
                    result = cart.CartDelete(itemName);
                }

            }
            else if (e.CommandName == "addQuantity")
            {
                int quantity = int.Parse(row.Cells[3].Text)   1;
                    cart.CartUpdateQuantity(quantity, itemName);
            }
            Response.Redirect("UserShoppingCart.aspx");
        }

And here is my aspx file:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <h1>Cart<table >
        <tr>
            <td style="width: 860px" >Product</td>
            <td style="width: 698px">Images</td>
            <td  style="width: 1265px">Quantity</td>
            <td>
                Price</td>
        </tr>
        <tr>
            <td colspan="4">
                <asp:GridView ID="CartGridView" runat="server" AutoGenerateColumns="False" Width="1514px" OnRowCommand="CartGridView_RowCommand" >
                    <Columns>
                        <asp:BoundField HeaderText="Product" ShowHeader="False" DataField="menuItemName" />
                        <asp:BoundField HeaderText="Images" ShowHeader="False" DataField="menuItemImage" />
                        <asp:ButtonField ButtonType="Button" CommandName="minusQuantity" Text="-" />
                        <asp:BoundField HeaderText="Quantity" DataField="totalQuantity" />
                        <asp:ButtonField ButtonType="Button" CommandName="addQuantity" Text=" " />
                        <asp:BoundField DataField="Total_Price" HeaderText="Price" ShowHeader="False" />
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td style="height: 39px; " colspan="3">Total:<asp:Label ID="lbl_TotalPrice" runat="server"></asp:Label>
            </td>
            <td style="height: 39px; width:50px;">
            </td>
        </tr>
        </table>
    </h1>
    

</asp:Content>

Could this issue arise from having an Sql Table as the datasource?

I have attempted,

string itemName = CartGridView.Rows[0].Cells[0].Text;

though it did work for the 1st row, I am uncertain on where to go next for the subsequent rows.

CodePudding user response:

The selected index change does not fire untill after the row command.

Why not just drop in a plane jane regular button? That way you can style the button, and just have a regular and simple click event for the button.

So, change your markup button to this:

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="cmdAddQty" runat="server" Text=" " 
                            OnClick="cmdAddQty_Click" />
                    </ItemTemplate>
                </asp:TemplateField>

So, just type in OnClick= (in the markup, and you be prompted for create new event). the result is a simple plain jane button click.

So, then the button click code can be:

    protected void cmdAddQty_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        GridViewRow gRow = (GridViewRow)btn.NamingContainer;

        Debug.Print("Row index click = "   gRow.RowIndex);

        int quantity = int.Parse(gRow.Cells[3].Text)   1;
        // cart.CartUpdateQuantity(quantity, itemName);

    }

So, you can easy pick up the row as per above.

And if you going to type "over and over" some sql, then build a helper rotuine to save world poverty, say like this:

protected void LoadCart()
{
    string strSQL =
        @"SELECT M.menuItemName, M.menuItemImage,totalQuantity, M.menuItemPrice * totalQuantity Total_Price
        FROM Cart C 
        INNER JOIN itemSelected I ON C.username   C.itemSelectedID = I.username   I.itemSelectedID
        INNER JOIN menuItem M ON I.menuItemID   I.stallID = M.menuItemID   M.stallID";
    CartGridView.DataSource = MyRst(strSQL);
    CartGridView.DataBind();
    LoadPrice();
}
protected void LoadPrice()
{
    string strSQL =
        @"SELECT SUM(M.menuItemPrice * totalQuantity)tabulatedPrice
        FROM Cart C 
        INNER JOIN itemSelected I ON C.username   C.itemSelectedID = I.username   I.itemSelectedID
        INNER JOIN menuItem M ON I.menuItemID   I.stallID = M.menuItemID   M.stallID";

    lbl_TotalPrice.Text = MyRst(strSQL).Rows[0][0].ToString();

}


DataTable MyRst(string strSQL)
{
    DataTable rstData = new DataTable();
    string strCon = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(strCon))
    {
        using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
        {
            cmdSQL.Connection.Open();
            rstData.Load(cmdSQL.ExecuteReader());
        }
    }
    return rstData;
}

Last but not least?

It is great to use and learn webforms. But, that is as long as you NOT paying for such a course, since webforms are now quite old, and while still rather popular? They are quite much now older and a legacy choice, one that been superseded by MVC and newer approaches.

So, I think WebForms are great, but NOT if you paying for books or a course in this day and age, and those peddling books and course(s) that teach webforms are really just using older outdated material, and thus taking a horrible advantage of un-suspecting students that don't know better.

Anyway, just drop in a plain jane regular button. You can dispense with row command and all that song and dance, as it not really required, and a simple regular button and button click event is easier anyway.

  • Related