Get total of a data row asp.net - asp.net

Im trying to get the values from each column in a single row to equal a total. Here is the code that im using to achieve this in c# asp.net
DataTable dt = ds.Tables.Add("InspireTable");
string pass = (String)Session["name"];
if (pass.Equals("High"))
{
dt.Columns.Add("Inspire", typeof(string));
dt.Columns.Add("SNS", typeof(int));
dt.Columns.Add("TT", typeof(int));
dt.Columns.Add("Music", typeof(int));
dt.Columns.Add("Total", typeof(string));
DataRow row = dt.NewRow();
row["Inspire"] = "Score";
row["SNS"] = 10;
row["TT"] = 10;
row["Music"] = 0;
dt.Rows.Add(row);
Chart1.DataSource = dt;
this.GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
}
Any ideas? I have tried calling each column and adding them but that seem not to work.

With the old DataTable.Compute method, for example:
int snsTotal = (int) dt.Compute("SUM(SNS)", null); // the second argument is the filter
Here's the "modern" Linq approach:
int snsTotal = dt.AsEnumerable().Sum(r => r.Field<int>("SNS"));
Edit: it seems as if you want to sum the numeric values of each row into a "total"-column. Then you can use a Column-Expression:
dt.Columns.Add("Total", typeof(int), "SNS + TT + Music");

Related

C# DataTable returns blank rows

Hello I am taking data from a one datatable that is coming from a session variable and trying to dump some of the data into new datatable however the new datatable returns empty? Empty meaning that there are rows present in the new table. ie., my gridview returns several blank rows?? Not sure what is happening to the string variables?
string date = DateTime.Now.ToShortDateString();
if (Session["MyData"] != null)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["MyData"];
DataTable newdt = new DataTable();
newdt.Columns.Add(new DataColumn("studentName"));
newdt.Columns.Add(new DataColumn("inter"));
newdt.Columns.Add(new DataColumn("CO"));
newdt.Columns.Add(new DataColumn("teacher"));
newdt.Columns.Add(new DataColumn("date"));
newdt.Columns.Add(new DataColumn("desc"));
DataRow newdr;
foreach (DataRow row in dt.Rows)
{
name = row["NM"].ToString();
term = row["term"].ToString();
Mark = row["Mark"].ToString();
period = row["period"].ToString();
CN = row["CN"].ToString();
CO = row["CO"].ToString();
PID = row["PID"].ToString();
//ADD TO NEW TABLE
newdr = newdt.NewRow();
name = newdr["studentName"].ToString();
dlInter.SelectedText = newdr["inter"].ToString();
CO = newdr["CO"].ToString();
teacher = newdr["teacher"].ToString();
date = newdr["date"].ToString();
LabelDescript.Text = newdr["desc"].ToString();
newdt.Rows.Add();
}
Repeater1.DataSource = newdt;
Repeater1.DataBind();
GridView1.DataSource = newdt;
GridView1.DataBind();
This line is your problem:
newdt.Rows.Add();
This will add an EMPTY row because the call to Add() without a DataRow or an object array is interpreted as adding a row without any value.
The solution is simple
newdt.Rows.Add(newdr);
Also the code before the Add is wrong because you are inverting the variables around the equal sign
newdr["studentName"] = name;
newdr["inter"] = dlInter.SelectedText;
newdr["CO"] = CO;
newdr["teacher"] = teacher
newdr["date"] = date;
newdr["desc"] = LabelDescript.Text;

add texbox values to gridview row in asp.net

int Row=0;
Row = PurchaseGridView.Rows.Count;
PurchaseGridView.Rows[Row].Cells[0].Text = ProductNameDropDown.SelectedValue.ToString();
PurchaseGridView.Rows[Row].Cells[1].Text = ProductNameDropDown.SelectedIndex.ToString();
PurchaseGridView.Rows[Row].Cells[2].Text = ProductPriceTxtBox.Text;
PurchaseGridView.Rows[Row].Cells[3].Text = QuantityTxtBox.Text;
PurchaseGridView.Rows[Row].Cells[4].Text = NetPriceTxtBox.Text;
i am adding values of textboxes in gridview like above, but it gives error.
Error: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
You have a few fundamental errors in your code:
You are using the Count to point to a new index which doesn't exists and thus you are getting the index out of range.
You cannot add rows to an asp.net gridview directly. You have to do it through a data binding. Here is an example:
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("ProductNameSelectedValue", typeof(string));
DataColumn dc = new DataColumn("ProductNameSelectedIndex", typeof(int));
..
Rest of you columns
..
DataRow dr = dt.NewRow();
dr["ProductNameSelectedValue"] = ProductNameDropDown.SelectedValue.ToString();
dr["ProductNameSelectedIndex"] = ProductNameDropDown.SelectedIndex;
..
Assign the rest of the columns
..
dt.Rows.Add(dr);
gv.DataSource = dt;
gv.DataBind();

How to bind gridview with some conditions in asp.net?

DataTable dtbind = new DataTable();
dtbind = objvehicleBAL.GetTaxdetails();
for (int i = 0; i < dtbind.Rows.Count; i++)
{
DateTime dt1 = DateTime.ParseExact(dtbind.Rows[i]["todate"].ToString(), "dd/MM/yyyy", null);
if (dt1 < ((DateTime.Now.AddDays(15))))
{
GVTax.DataSource = dtbind.Rows[i];
GVTax.DataBind();
}
}
I had written my conditions in if(). I want to bind only satisfied rows in grid. How can I write this?
You do not need to bind the Grid in loop on the Row of data table rather filter the DataTable by the condition you want and bind it once. You can get DataView from the data table and use its property DataView.RowFilter to apply the date filter.
dtbind = objvehicleBAL.GetTaxdetails(); //Filter the record in GetTaxdetails
DataView dv = dtbind.DefaultView; //or use DataView with RowFilter
dv .RowFilter = "todate = #" + DateTime.Now.AddDays(15).ToString() + "#";
GVTax.DataSource = dv;
GVTax.DataBind();
DataTable dtbind1 = objvehicleBAL.GetTaxdetails();
DataTable dtbind2 = new DataTable();
foreach (DataRow row in dtbind1.Rows)
{
DateTime dt1 = DateTime.ParseExact(row["todate"].ToString(), "dd/MM/yyyy", null);
if (dt1 < ((DateTime.Now.AddDays(15))))
dtbind2.Rows.Add(row);
}
}
GVTax.DataSource = dtbind2;
GVTax.DataBind();
No need to bind each row and call DataBind mehtod each time.
Just use the following:
protected void BindGrid()
{
DataTable dtbind = new DataTable();
dtbind=objvehicleBAL.GetTaxdetails();//get the rows filtered in SQL
if(dtbind!=null && dtbind.Rows.Count>0)//always check for null for preventing exception
{
GVTax.DataSource = dtbind;
}
GVTax.DataBind();
}
Hope this helps you!
You can use the Select method of DataTable along with a filtering expression, to get the rows which match your criteria. Then, bind it to to your GridView.
string filterExp = "todate < dateadd(day,15,getdate())";
var filtered = dtBind.Select(filterExp);
GVTax.DataSource = filtered ;
GVTax.DataBind();
You can create another datatable and fill the rows satisfying your condition in the second datatable and bind your gridview with second datatable (having filtered rows)
dttableNew = dttableOld.Clone();
foreach (DataRow drtableOld in dttableOld.Rows)
{
if (/*put some Condition */)
{
dtTableNew.ImportRow(drtableOld);
}
}
GVTax.DataSource = dtTableNew;
GVTax.DataBind();

how to update gridview row using viewstate

I am using a gridview with viewstate.
here I want to update gridview row. The gridview contains 4 columns
Insertion and deletion process are done. But I don't know how to update row with view state. can anyone help me??
if (ViewState["PdataTable"] == null)
{
TempDTable.Columns.Add("QuestionID", typeof(string));
TempDTable.Columns.Add("ColumnName", typeof(string));
TempDTable.Columns.Add("ColumnType", typeof(string));
TempDTable.Columns.Add("OptionValues", typeof(string));
}
else
{
TempDTable = (DataTable)ViewState["PdataTable"];
}
DataRow row;
row = TempDTable.NewRow();
TextBox txtftrColName = (TextBox)GridViewColumns.FooterRow.FindControl("txtftrColName");
DropDownList DrpType = (DropDownList)GridViewColumns.FooterRow.FindControl("DrpType");
TextBox txtValues = (TextBox)GridViewColumns.FooterRow.FindControl("txtValues");
row["QuestionID"] = Qst3.Text;
row["ColumnName"] = txtftrColName.Text;
row["ColumnType"] = DrpType.SelectedItem.Text;
row["OptionValues"] = txtValues.Text;
TempDTable.Rows.Add(row);
ViewState["PdataTable"] = TempDTable;
this.GridViewColumns.Visible = true;
GridViewColumns.DataSource = TempDTable;
GridViewColumns.DataBind();

Regarding binding array to gridview

Hi
I have created session array :
int[] a = (int[])Session["values"];
Now i have to bind this value to my gridview. I have one column (boundfield in my gridview) in gridview.
I used code to bind array to gridview as follows, but its giving last value only as i want all the values to bind :
for (int i = 0; i < a.Length; i++)
{
str = "select * from Quest_Info where Quest_id='" + a[i] + "' order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();
}
Which code will work for this?
Asp.net, c#
Thank You.
Your code may not work because you are trying to bind gridview in the for loop which keep repeating and will result to bind only one last array id in the end.
You may try to prepare query out front before binding the gridview as example below.
string questIds = string.Empty;
for (int i = 0; i < a.Length; i++)
{
if (questIds.Length > 0)
questIds += ", ";
questIds += a[i];
}
string strSQL = "select * from Quest_Info where Quest_id IN ("+ questIds + ") order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();

Resources