I have a GridView with two columns. The first shows a date and the second, the year of the date in the first column. So far everything works well but when I change page, the web fails with the message: "Object reference not set to an instance of an object."
This is my code:
Test.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="qq_site_Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>TEST</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5"
AllowSorting="True" AutoGenerateColumns="False"
EnableModelValidation="True" onrowcreated="GridView1_RowCreated"
onpageindexchanged="GridView1_PageIndexChanged"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="creationDate" HeaderText="creationDate" SortExpression="creationDate" />
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Test.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.Data;
public partial class qq_site_Test : System.Web.UI.Page
{
static DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
String connectionString = "DSN=kitchenmaster.es.qq-site;";
String sqlQuery = "SELECT * FROM tblSystems WHERE ID < 100";
ds = new DataSet();
OdbcConnection connection = new OdbcConnection(connectionString);
OdbcCommand command = new OdbcCommand(sqlQuery, connection);
OdbcDataAdapter adapter = new OdbcDataAdapter(command);
try
{
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
DateTime dt = (DateTime)DataBinder.Eval(e.Row.DataItem, "creationDate");
e.Row.Cells[GetColumnByID("Year")].Text = dt.Year.ToString();
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
}
}
protected int GetColumnByID(String columnName)
{
foreach (DataControlField column in GridView1.Columns)
{
if (column.HeaderText == columnName)
return GridView1.Columns.IndexOf(column);
}
return -1;
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
GridView1.SelectedIndex = -1;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (e.NewPageIndex != -1)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
catch (System.Exception ex)
{
Response.Write(ex.Message);
}
}
}
Can you help me?
This line of code
GridView1.DataSource = ds;
is probably where you are getting the error.
When the GridView1_PageIndexChanging event is called, you have not yet set the value for ds. The only part in your code that does so is in the Page_Load event, and only when it's not a postback.
If I check the value of the e.Row.DataItem in the event GridView1_RowCreated(), the error not occurs but I don't know if it's the right thing to do. The new version of the event is:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
if (e.Row.DataItem != null)
{
DateTime dt = (DateTime)DataBinder.Eval(e.Row.DataItem, "creationDate");
e.Row.Cells[GetColumnByID("Year")].Text = dt.Year.ToString();
}
}
catch (System.Exception ex)
{
Response.Write("** " + ex.Message);
}
}
}
Please check your "ds" object inside in PageIndexChanging event.
First fill the data set and bind.
Related
I am making a Attendance System in which I get Student Record from student table in a Gridview with a check box. tick the check box for students present and leave unchecked for absent.
After that i submit my record to attendance system.
Problem: If I Check or left unchecked it will show the Absent in Database Results after submission of attendance please check my code.
HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="RecordTablesss.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelSr" runat="server" Text=<%#Eval("Sr_Number") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelName" runat="server" Text=<%#Eval("Name") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LabelFN" runat="server" Text=<%#Eval("F_Name") %>></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckAttendence" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="SaveAttendence" style="width: 61px" />
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace RecordTablesss
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
loadData();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void loadData()
{
SqlConnection con = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select Sr_Number,Name,F_Name From Registerd_Student",con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void SaveAttendence(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
string sta = "A";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
sta = "P";
string StudentName = (row.FindControl("LabelName") as Label).Text;
string F_Name = (row.FindControl("LabelFN") as Label).Text;
int Number = int.Parse( (row.FindControl("LabelSr") as Label).Text);
//From Here to onword Database Operations. ..
SqlConnection conn = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert into Attendance_B values('"+Convert.ToInt32(Number)+"','"+StudentName+"','"+F_Name+"','"+sta+"')",conn);
cmd.ExecuteNonQuery();
}
}
}
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
}
}
}
As You said #Thomas Krojer Answer also not solving your issue but it should do.
The resone you are getting chkVar_.Checked always false.because On Page_Load you are binding gridview again with out checking if it is a postback.
Try this.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadData();
}
}
It will solve your problem surely..
I think you do not really write what you mean:
string sta = "";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
sta = "P";
sta = "A";
I thin you mean:
string sta = "";
CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
if (chkVar_.Checked)
{
sta = "P";
}
else
{
sta = "A";
}
you see the difference?
you just need to correct code
if (chkVar_.Checked)
{
sta = "P";
}
else
{
sta = "A";
}
In my C# application, I am generating a Gridview from user's input and then I have to give user an option to export the Gridview to the excel sheet.
Here is my abc.aspx page:
<body>
<form id="form1" runat="server">
<div>
<b>Enter p1 :</b>
<asp:TextBox ID="tb_P1" runat="server" />
<br />
<b>Enter p2 :</b>
<asp:TextBox ID="tb_P2" runat="server" /><br />
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="Start Search" ClientIDMode="Static" />
<asp:Button ID="btn2" runat="server" OnClick="Button2_Click" Text="Export Data to Excel" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
ShowFooter="false"
AllowSorting="true"
OnSorting="GridView1_Sorting"
EnableViewState="false"
ShowHeaderWhenEmpty="True"
AllowPaging="false">
<RowStyle Wrap="false" />
<HeaderStyle Wrap="false" />
</asp:GridView>
</div>
</form>
<br />
</body>
Here my .cs page:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Services;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.IO;
public partial class pSearch : System.Web.UI.Page
{
SqlConnection sqlconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
DataSet dsldata;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
string fname = filename.Text;
GridView1.DataSource = (DataSet)Session["data"];
GridView1.DataBind();
int rowCount = GridView1.Rows.Count;
if (rowCount == 0)
{
Response.Write("<script>alert('Result Empty!');</script>");
}
else
{
ExportToExcel(GridView1, fname);
}
}
private void ExportToExcel(GridView GrdView, string fname)
{
try
{
Response.AddHeader("contentdisposition", "attachment;filename=test1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
GrdView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string Rname= Page.Request.QueryString["rname"];
string typeofquery = "my command";
string abc = null;
abc = "" + typeofquery + " #RName='" + RName "'";
SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);
cmdldata.SelectCommand.CommandTimeout = 600;
dsldata = new DataSet();
try
{
cmdldata.Fill(dsldata);
Session["data"] = dsldata;
GridView1.DataSource = dsldata;
GridView1.DataBind();
}//end of try
catch (Exception ex)
{
Response.Write(ex);
}//end of catch
}
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
dsldata = (DataSet)HttpContext.Current.Session["data"];
DataTable dt = dsldata.Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
dt = dv.ToTable();
DataSet ds1 = new DataSet("table");
ds1.Tables.Add(dt);
Session["data"] = ds1;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
I have sorting enabled in my gridview.
The problem is: my whole web page is getting exported to the excel sheet. I want only my grid view to be exported.The sorting is working properly and I do get new sorted table in my excel sheet but it is with the whole web page.
I have looked for solution on different places on internet.Seems like many people have faced this problem.I have also tried their solutions like
changing the Response.ContentType = "application/vnd.xls"; to
Response.ContentType = "application/vnd.ms-excel"; and most of the other solutions were similar to my ExportToExcel() function.
I have been wokring on this thing since last 2 days but nothing is working for my application.
Please Help!
Thank you in advance!
Changed my ExporttoExcel function
private void ExportToExcel(GridView GrdView, string fname)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + fname + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
I have solved this problem.I realized that the problem was in AllowSorting feature of my gridview.I turned off the eventvalidation of that page.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="abc.aspx.cs" Inherits="abc" EnableEventValidation = "false" %>
This worked!
I think you need Response.Clear() at the top of your Export ToExcel() function.
I'm not able to bind my dropdownlist present in edititem template . I am getting null reference when i try to access it.
My design:
<asp:TemplateField HeaderText ="Category">
<ItemTemplate >
<asp:Label ID="drpcategory" Text ='<%#Bind("category") %>' runat ="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpcategory1" AppendDataBoundItems="True" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
My code behind:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_table1.EditIndex = e.NewEditIndex;
DropDownList drpcategory1 = ((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1"));
//BindDropDown(drpcategory1);
dt = con.GetData("Select category_name from category");
String str = gv_table1.Rows[e.NewEditIndex].FindControl("drpcategory1").GetType().ToString();
//((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1")).DataSource = dt;
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
this.setgrid();
}
I've tried looking on the net and tried many things in vain. I am new to asp. Thanks in advance. I would like the dropdown to be bound only when user enters edit mode.
Code Behind: Tested Code and also set dropdown-list selected value on edit mode
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("drpcategory1");
//bind dropdown-list
DataTable dt = con.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "category_name";
ddList.DataValueField = "category_name";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = dr["category_name"].ToString();
}
}
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
gridviewBind();// your gridview binding function
}
I do it like this. In which, Name and Id are two fields of Company object:
HTML Code:
<asp:TemplateField HeaderText="Công ty">
<EditItemTemplate>
<asp:DropDownList ID="ddlCompanyEdit" DataSource="<%# PopulateddlCompanyEdit() %>" DataValueField="Id" DataTextField="Name" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbCompany" runat="server" Text='<%#Bind("Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C# code behind:
protected IEnumerable<Company> PopulateddlCompanyEdit()
{
using (var bkDb = new BrickKilnDb())
{
return bkDb.Companies.ToList();
}
}
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
string Active = "";
if (e.Row.DataItem != null)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblEditActive = (Label)e.Row.FindControl("lblUP_ET_ActiveStatus");
if (lblEditActive.Text != string.Empty)
{
Active = lblEditActive.Text.Trim();
}
DropDownList ddlActive = (DropDownList)e.Row.FindControl("ddlUP_ET_ActiveStatus");
ddlActive.Items.Clear();
ddlActive.Items.Add("True");
ddlActive.Items.Add("False");
ddlActive.DataBind();
ddlActive.Items.FindByText(Active).Selected = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The event RowEditing occurs just before a row is edited.
You should use the RowDataBound event instead.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gv.EditIndex == e.Row.RowIndex &&
e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
//bind the control
}
}
You have to use RowDataBound event to bind the dropdown control for edited row. Please use below method in RowDataBound event.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
DataTable dt = con.GetData("Select category_name from category");
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
}
}
Hope this will help you.
This seems to be an easy question to ask, but I am not able to show items in GridView. Here is my code:
public partial class TestList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ TestProject.DataAccess.Repository.Instance.Initialize(Settings.Default.TestConnection);
BindData();
}
}
private void BindData()
{
//Restriction Info!!
gvAgentList.DataSource = EntityRegistration.DataAccess.Repository.Instance.GetData();
gvAgentList.DataBind();
}
protected void gvAgentList_PageIndexChanging (object sender, GridViewPageEventArgs e)
{
gvAgentList.PageIndex = e.NewPageIndex;
gvAgentList.DataBind();
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected void gvAgentList_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gvAgentList.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gvAgentList.DataSource = dataView;
gvAgentList.DataBind();
}
}
}
Here is the markup of the GridView:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
Agent Lists:</p>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView runat ="server" ID = "gvAgentList"
AllowPaging = "True"
AutoGenerateSelectButton="True" AllowSorting="True" BackColor="#E8E8E8"
BorderColor="#003399" BorderStyle="Solid" BorderWidth="1px" Height="375px"
Width="731px" OnPageIndexChanging = "gvAgentList_PageIndexChanging"
OnSorting="gvAgentList_Sorting" >
<AlternatingRowStyle ForeColor="#0066CC" />
<HeaderStyle ForeColor="#3366FF" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The problem is that my GridView is not throwing me any exception and through breakpoints I can see that the function is called in code behind.
My sorting is also not working :(
Try
protected void gvAgentList_PageIndexChanging (object sender, GridViewPageEventArgs e)
{
gvAgentList.PageIndex = e.NewPageIndex;
BindData();
}
Set pageindex property of gridview e.g. PageIndex="10"
I will post you my code and i will explain what i want to do
<div>
<div>
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="hdValue" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="btnMove" runat="server" Text="Add To Cart" OnClick="btnMove_Click" />
</div>
<div>
<asp:GridView ID="gridView2" runat="server">
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="tbQty" runat="server" Width="25px"
MaxLength="3" />
</ItemTemplate>
<ItemStyle Width="25px" HorizontalAlign="Center"/>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:Button ID="Button1" runat="server" Text="Find the total" />
<asp:Label ID="Label7" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<br />
<br />
</div>
and the theo.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class theo : System.Web.UI.Page
{
const string key = "MyDataSource5";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
if (Session[key] == null)
{
gridView1.DataSource = GetDataSource();
gridView1.DataBind();
}
else
{
gridView1.DataSource = (DataTable)Session[key];
gridView1.DataBind();
}
}
protected DataTable GetDataSource()
{
try
{
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price(Grouch)/Hectares", typeof(float));
DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["ID"];
dt.PrimaryKey = keys;
dt.Rows.Add("1", "Seaside Location", 1.5);
dt.Rows.Add("2", "Arable Land", 0.1);
dt.Rows.Add("3", "Foothills of the mountains", 1.5);
dt.Rows.Add("4", "Industrial Land", 0.1);
dt.Rows.Add("5", "Rolling Farmland", 0.5);
Session[key] = dt;
return dt;
}
catch
{
return null;
}
}
protected void btnMove_Click(object sender, EventArgs e)
{
try
{
DataTable dtMain = Session[key] as DataTable;
//copy the schema of source table
DataTable dtClone = dtMain.Clone();
foreach (GridViewRow gv in gridView1.Rows)
{
CheckBox chk = gv.FindControl("chkSelect") as CheckBox;
HiddenField hdValue = gv.FindControl("hdValue") as HiddenField;
if (chk.Checked)
{
//get only the rows you want
DataRow[] results = dtMain.Select("ID=" + hdValue.Value + "");
//populate new destination table
foreach (DataRow dr in results)
{
dtClone.ImportRow(dr);
}
}
gridView2.DataSource = dtClone;
gridView2.DataBind();
}
}
catch
{
BindGridView();
}
}
}
In this code when i check for example 2 choices from gridview 1 and click the button add to cart then these 2 choices are moving to the second gridview. As you see,I have a textbox for the quantity. I would like when i give the quantity to multiply it with the price.With the button 'find the total' i want to give me the result in the text box.How can i do that?
one simple solution may be useful to you.
protected void Button1_Click(object sender, EventArgs e)
{
int itemCount;
decimal itemPrice, itemTotal;
itemTotal = 0;
itemCount = 0;
itemPrice = 0;
foreach(GridViewRow gridView2Row in gridView2.Rows)
{
TextBox tbCount = gridView2Row.Cells[0].Controls[1] as TextBox;
itemCount = Convert.ToInt32(tbCount.Text);
itemPrice = Convert.ToDecimal(gridView2Row.Cells[3].Text);
itemTotal = itemTotal + (itemCount * itemPrice);
}
TextBox1.Text = itemTotal.ToString();
}