how to update gridview row using viewstate - asp.net

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

Related

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

Paging and Sorting in Asp.net Repeater Control

In following code i am trying to show the latest record on the top of repeater. I also want to include paging in repeater.Paging is done successful in page but i am having trouble when i do sorting in repeater.So my question is this that how can i do sorting and paging in repeater?
My code:
private void Get_Data()
{
String File = Server.MapPath("~/Data/BlogContent.xml");
DataSet ds = new DataSet();
ds.ReadXml(File);
DataView dv = new DataView(ds.Tables[0]);
dv.Sort = "id DESC";
DataTable dt = dv.Table;
ViewState.Add("Mytable", dt);
}
private void Bind_Data(int take, int pageSize)
{
PagedDataSource page = new PagedDataSource();
page.AllowCustomPaging = true;
page.AllowPaging = true;
DataTable dtv = (DataTable)ViewState["Mytable"];
DataView dv = new DataView();
dv = dtv.DefaultView;
dv.Sort = "id ASC";
dv.RowFilter = "id>=" + pageSize + " AND " + "id<=" + take;
page.DataSource = dv;
page.PageSize = psize;
Repeater1.DataSource = page;
Repeater1.DataBind();
if (!IsPostBack)
{
int rowcount = dtv.Rows.Count;
CreatePagingControl(rowcount);
}
}
For paging Check this.Here is full example of paging.link
paging and sorting
** Read the article:
Custom paging in Repeater control in asp.net(C#, VB)**
http://www.webcodeexpert.com/2013/05/custom-paging-in-repeater-control-in.html

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

How to change Column Width of GridView programically

I have GridView that is filled programically using List of Object. I can't access to Columns in GridView. I like to put Width of Columns programically?Here is the code how I fill the GridView
DataClassesDataContext dContext = new DataClassesDataContext();
var userId = (Guid)(Membership.GetUser(Membership.GetUser().UserName, false).ProviderUserKey);
var tekovenKorisnikQuery = from d in dContext.pregledIshranas
where d.UserId == userId
select new {d.datum, d.kilogrami, d.visina, d.BMI, d.kalorii};
List<PregledIshranaFormatirano> listaFormatirana = new List<PregledIshranaFormatirano>();
foreach (var d in tekovenKorisnikQuery)
{
listaFormatirana.Add(new PregledIshranaFormatirano(string.Format("{0:dd-MM-yyyy}", d.datum), d.kilogrami.ToString(), d.visina.ToString(), string.Format("{0:N2}", d.BMI), d.kalorii.ToString()));
}
gvTekovenKorisnik.DataSource = listaFormatirana;
gvTekovenKorisnik.DataBind();
I use this event handler to change header
protected void gvTekovenKorisnik_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Width = new Unit("200px");
e.Row.Cells[0].Text = "Датум";
e.Row.Cells[1].Width = new Unit("200px");
e.Row.Cells[1].Text = "Килограми";
e.Row.Cells[2].Width = new Unit("200px");
e.Row.Cells[2].Text = "Висина";
e.Row.Cells[3].Width = new Unit("200px");
e.Row.Cells[3].Text = "BMI индекс";
e.Row.Cells[4].Width = new Unit("200px");
e.Row.Cells[4].Text = "Калории";
}
In this way the width isn't changed and I can't access to gridView columns.
Could somebody help me?
You can change column widths right after GridView DataBind() method call.
For example: gvTekovenKorisnik.Columns[0].Width = %yourvalue%;

Resources