C# DataTable returns blank rows - asp.net

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;

Related

upload a Excel file without header in Grid View (already defined column names) in asp .net C#, each time it show error when reaches at dt.Rows.Add()

here the code which i am using to import excel to grid view.. Each time getting error at dt.Rows.Add()
here the error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.Couldn't store in SUPPLY DATE Column. Expected type is DateTime."
in .aspx page i don't defined any column with datetime
DataTable dtExl = conUpLoad.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExl.Rows[0]["Table_Name"].ToString();
OleDbCommand ExcelCommand = new OleDbCommand("Select * From [" + getExcelSheetName + "]", conUpLoad);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
DataSet ExcelDataSet = new DataSet();
ExcelAdapter.Fill(ExcelDataSet);
//conUpLoad.Close();
// Clearing the grid ::::::::::::::::::::::
ViewState["dt"] = null;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
// ::::::::::::::::::::::::::::::::::::::::
DataTable dt = ExcelDataSet.Tables[0];
int i = 0;
if (ExcelDataSet.Tables[0].Rows.Count > 0)
{
String DINumber = ExcelDataSet.Tables[0].Rows[0][0].ToString();
String PartNo = ExcelDataSet.Tables[0].Rows[0][1].ToString();
String DeliveryDt = Convert.ToDateTime(ExcelDataSet.Tables[0].Rows[0][3].ToString()).ToString("dd-MMM-yyyy");
String Location = ExcelDataSet.Tables[0].Rows[0][5].ToString();
String Qty = ExcelDataSet.Tables[0].Rows[0][7].ToString();
String PartyCode = ExcelDataSet.Tables[0].Rows[0][10].ToString();
dt.Rows.Add(DINumber, PartNo, DeliveryDt, Location, Qty, PartyCode);
ViewState["dt"] = dt;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
i++;
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}

how to INSERT item in drop down list at the index other than 0 to "n"?

I want to insert an item in drop down list at an index other than 0. I've bound my drop down datavaluefield with identity starting from 1 and want to insert an item on selected value other than 0 to "n", n being any number. Can I get some help?
here's my code:
public void Bind_ddlSelectGroup()
{
using(SqlCommand cmd = new SqlCommand("select g.GroupId, g.GroupName from timeOtime.dbo.[Group] as g where IsDeleted=0", Database.con))
{
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
ddlSelectGroup.DataSource = null;
ddlSelectGroup.DataSource = ds.Tables[0];
ddlSelectGroup.DataTextField = "GroupName";
ddlSelectGroup.DataValueField = "GroupId";
ddlSelectGroup.DataBind();
}
}
ddlSelectGroup.Items.Insert(0, new ListItem("--Select All Groups--", "0"));
}
I want to insert an item as "--Ungrouped--" in dropdown.
I figured it out. I added the required item("--Ungrouped--") at the bottom of dropdownlist.
ddlSelectGroup.Items.Insert(ddlSelectGroup.Items.Count, new ListItem("--Ungrouped--", "ungrouped"));
it worked fine.

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();

Get total of a data row 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");

Resources