i have a gridview which gets it values from a database in MS SQL Server 2014. The grid view has four columns from database (namely p_id, p_image, p_name, p_price) and followed by 2 additional columns, a dropdownlist and a checkbox and there is a textbox below the gridview.
My requirement is when I check the check box, the value from the price column of the selected row is to be multiplied with the value from the dropdownlist control and displayed in the textbox.
And again when I check another checkbox, I want the value of price column of this selected row to be multiplied with its dropdownlist value and added to the previous value of the textbox and displayed in the same textbox. The code I have used for that is :
public double sum = 0 ;
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gvPackaged.Rows)
{
CheckBox chk = (row.Cells[5].FindControl("chkSelect") as CheckBox);
DropDownList ddl = (row.Cells[4].FindControl("ddlSelect") as DropDownList);
if (row != null && chk != null)
{
if (chk.Checked)
{
double quantity = Convert.ToDouble(ddl.Text);
double price = Convert.ToDouble(row.Cells[3].Text);
sum += (price * quantity);
tbTotal.Text = Convert.ToString(sum);
}
}
}
}
The above code is working but the problem is every time I check the checkbox, the onCheckedChanged method is called and it will iterate through all the rows in the gridview and then displays the value in the textbox which makes the process considerably slow.
I have searched in many forums including this one and found only this approach is being used in almost every question and answer.
the only other approach is :
GridViewRow row = myGridview.SelectedRow;
instead of
foreach (GridViewRow row in myGridview.Rows)
and hence I used that in my code :
public double sum = 0 ;
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = gvPackaged.SelectedRow;
CheckBox chk = (row.Cells[5].FindControl("chkSelect") as CheckBox); //HERE
DropDownList ddl = (row.Cells[4].FindControl("ddlSelect") as DropDownList);
if (row != null && chk != null)
{
if (chk.Checked)
{
double quantity = Convert.ToDouble(ddl.Text);
double price = Convert.ToDouble(row.Cells[3].Text);
sum += (price * quantity);
tbTotal.Text = Convert.ToString(sum);
}
}
}
And then this error occurred in the above code on the //HERE line:
NullReferenceException
which means that exception occurred with the row var in the line above, and
Object reference not set to an instance of an object.
Again I searched for it and found it to be a general exception and did not find a sol specific to my problem.
Can anyone PLEASE help me to retrieve the current selected row into the row variable so that I can perform calculations using that row directly without having to use loops and iterate.
Aucun commentaire:
Enregistrer un commentaire