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();
Related
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;
My datatable contain column "Date" that have data like this in the following
'2013-01-01',
'2013-05-01',
'2014-01-01',
'2014-12-25',
'2014-12-26
But i want to get data something like 'select distinct year(Date)', and bind selected data into dropdownlist
however, syntax error message popup: "Syntax error: Missing operand after 'year' operator."
can I get any support? THANKS!!!!
private DataTable BuildDT(string [] date)
{
DataTable dt = new DataTable("test");
dt.Columns.Add("RowID", typeof(Int16));
dt.Columns.Add("Date", typeof(DateTime));
for (int i = 0; i < date.Length; i++)
{
dt.Rows.Add(i+1,date[i]); // {1,2013-01-01}
}
return dt;
}
private void ddlGetData2(DataTable table)
{
table.DefaultView.RowFilter = "distinct year(Date)";
DropDownList1.DataSource = table;
DropDownList1.DataBind();
}
You can do this with LINQ...
var years = table.AsEnumerable()
.Select(r => r.Field<DateTime>("Date").Year)
.Distinct()
.OrderBy(y => y)
.ToList();
You can use the .ToTable() on the associated DataView instance.
var dv = dt.DefaultView;
var distinctDates = dv.ToTable(true, "Date");
I have a datatable, then I have all the column names of the datatable as checkbox, I want to display only those column records, for which user selected from the checkbox:
Below is the code, but I am not getting the desired result
var values = "";
string clmnm = "";
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected)
{
values += interestedIN.Items[i].Value + ",";
}
}
values = values.TrimEnd(',');
string[] words = values.Split(',');
DataTable dt = new DataTable();
dt = (DataTable)Session["dataset"];
DataTable dt1 = new DataTable();
foreach (string word in words)
{
dt1.Columns.Add(word, typeof(string));
if (clmnm == string.Empty)
{
clmnm = word.Trim();
}
else
{
clmnm += "," +word.Trim();
}
}
foreach (DataRow dr in dt.Rows)
{
string[] split = clmnm.Split(',');
int j =0;
string str = "";
string str2 = "";
while( j < split.Length)
{
str = split[j].ToString();
if (str2 == string.Empty)
{
str2 = "dr[\""+str.ToString()+"\"]";
}
else
{
str2 += "," + "dr[\""+str.ToString()+"\"]";
}
j+=1;
}
dt1.Rows.Add(str2);
}
then I am trying to export the result as an excel sheet: but getting the below excel sheet:
There is a lot of changes to be done to your code. Lets begin with selected columns from CheckBoxList. Try using List or Arrays to store which columns that user wants. Like
List<string> columns = new List<string>();
Then store the selected columns into the columns list. Then you need to add columns to your new DataTable dt1. As,
DataTable dt1 = new DataTable();
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected) //If user selected this columns checkbox.
{
columns.Add(interestedIN.Items[i].Text.Trim()); //Storing values to List.
dt1.Columns.Add(interestedIN.Items[i].Text.Trim()); //Adding columns to the DataTable.
}
}
Then you can loop through your original DataTable dt and store the values as below.
foreach (DataRow dr in dt.Rows)
{
DataRow dr1 = dt1.NewRow(); // Create new row which should have identical structure for inserting.
foreach(string col in columns)
{
dr1(col) = dr(col);
}
dt1.Rows.Add(dr1); //Add the row with the contents to the table.
}
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");
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();