Hey Friends...
i want a simple example to display a sum of two values in database.
in database i have
id, one and two as row
in default.aspx
I have 2 text box
and one submit button
on clicking to submit button.. values of both the two text box got saved in database
and i can display them on gridview.. by using databind.
now i want that there should be a 3rd column in Gridview which display the total of two numbers.. (1+1 = 3) i.e 3 should be displayed but it's values (3) should not be saved in database.
every time when i run... it display the total of all numbers which are saved in database
example.
one two sum
1 1 2
2 2 4
2 5 7
etc.
plz help me as i'm new in asp.
Loading
Satyapriya NayakPosted Feb 6, 2013, 1:39 AM
Thanks
Satyapriya NayakPosted Feb 5, 2013, 7:32 AM
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace Sum
{
public partial class _Default : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand com;
SqlDataAdapter sqlda;
DataSet ds;
string str;
protected void Page_Load(object sender, EventArgs e)
{
bindgrid();
}
private void bindgrid()
{
SqlConnection con = new SqlConnection(connStr);
con.Open();
str = "select *,(one + two)as 'Sum' from test";
com = new SqlCommand(str, con);
sqlda = new SqlDataAdapter(com);
ds = new DataSet();
sqlda.Fill(ds, "test");
GridView1.DataMember = "test";
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connStr);
com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText = "insert into test values(@one,@two)";
com.Parameters.Clear();
com.Parameters.AddWithValue("@one", txtOne.Text);
com.Parameters.AddWithValue("@two", txtTwo.Text);
if (con.State == ConnectionState.Closed)
con.Open();
com.ExecuteNonQuery();
con.Close();
bindgrid();
}
}
}
Thanks
If this post helps you mark it as answer
Jignesh TrivediPosted Feb 5, 2013, 7:21 AM
hi,
you may use RowDataBound even of Grid view.
this event is fired when your datasource is bind with grid view. also this event is available for each of row.
try...
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].Text = Convert.ToInt32(e.Row.Cells[0].Text) + Convert.ToInt32(e.Row.Cells[1].Text);
}
}
replace your original column id with this example
hope this will help you.