create custom gridview template fields for a List<> - asp.net

I have a List of Lists of string . I want to show it to user using a gridview . as number of columns are not known I decided to create gridview fields dynamically . I found some tutorials but all of them use DataTable . I tried to use the same but I have problem with databinding event's "_columnName" :
void field_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}
as there is no column in list . any suggestion is appreciated .

A much easier way would be to set AutoGenerateColumns to true and use a DataTable as DataSource.
For example ( the aspx can be an empty GridView ):
List<List<String>> data = new List<List<String>>() {
new List<String>(){"Row1_Col1", "Row1_Col2", "Row1_Col3"},
new List<String>(){"Row2_Col1", "Row2_Col2", "Row2_Col3"},
new List<String>(){"Row3_Col1", "Row3_Col2", "Row3_Col3"},
new List<String>(){"Row4_Col1", "Row4_Col2", "Row4_Col3"},
new List<String>(){"Row5_Col1", "Row5_Col2", "Row5_Col3"},
};
var tbl = new DataTable();
int maxFieldCount = data.Max(l => l.Count);
for (int i = 1; i <= maxFieldCount; i++)
tbl.Columns.Add("Column" + i);
foreach (var list in data)
{
DataRow newRow = tbl.Rows.Add();
newRow.ItemArray = list.ToArray();
}
now it can be used as DataSource of the GridView:
GridView1.DataSource = tbl;
GridView1.DataBind();

Related

how to get gridview all rows data when using paging

I have a gridview with paging (page size 10), which contains Course details. when i am saving gridview data into database it save only 10 record (according to page).
is there any to get all gridview all rows.
e.g. if my gridview contains 25 rows with paging and when i save data into database then all 25 rows data insert into database?
please help...
Here is my code
DataTable dt = new DataTable();
dt.Columns.Add("row_index");
dt.Columns.Add("edited_value");
IList<int?> SeqNos = new List<int?>();
foreach (GridViewRow gvr in gvViolationCodes.Rows)
{
TextBox tb = (TextBox)gvr.FindControl("txtSeqNo");
Label lblSysid = (Label)gvr.FindControl("lblSysID");
HiddenField hf = (HiddenField)gvr.FindControl("HiddenField1");
if (tb.Text != hf.Value)
{
DataRow dr = dt.NewRow();
SeqNos.Add(Convert.ToInt32(tb.Text));
dr["row_index"] = lblSysid.Text;
dr["edited_value"] = tb.Text;
dt.Rows.Add(dr);
}
}
You need to save the data in temporary storage in PageIndexChanging event of GrIdView. On final save send the datatable to Sql Server Procedure or loop through the datatable and save it in database. Follow the steps:
protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
fnStoreGridData();
}
private void fnStoreGridData()
{
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
else{
TempDataTable.Columns.Add("exCourse", typeof(string)) ;
TempDataTable.Columns.Add("exUniversityCourse", typeof(string)) ;
}
foreach (GridViewRow row in gvExportCourse.Rows)
{
Label exCourse = (Label)row.FindControl("gvlblCourseName");
Label exUniversityCourse = (Label)row.FindControl("gvlblUniversityCourseName");
if (exCourse != null)
{
if (!string.IsNullOrEmpty(exCourse.Text))
{
TempDataTable.Rows.Add(exCourse.Text, exUniversityCourse.Text);
//TempDataTable is your datatable object. Make sure that datatable contains these columns
}
}
}
}
In Final Save:
protected void button_Click(object s, EventArg e)
{
fnStoreGridData(); //Here this will bind the data of current page
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
//Now loop through datatable and store the values
foreach(DataRow in TempDataTable.Rows)
{
CourseInformation course = new CourseInformation();
course.AddCourseMaster(dr["exCourse"].ToString(), dr["exUniversityCourse"].ToString());
}
label1.Text = "Course saved successfully.";
}

How to add and update rows in gridview asp.net

I am doing an online ordering system. I want to check if the item exist in the gridview so it will not add another row or have multiple lines (It will update the qty and the price). The gridview is updating using dgvOrder.Rows[i].Cells[2].Text but my problem is how to update the datatable.
bool isExist = false;
if (Session["dtInSession"] != null)
dt = (DataTable)Session["dtInSession"]; //Getting datatable from session
for (int i = 0; i < dgvOrder.Rows.Count; i++)
{
if (dgvOrder.Rows[i].Cells[0].Text == b.ID)
{
isExist = true;
dgvOrder.Rows[i].Cells[2].Text = Convert.ToString(Convert.ToInt32(dgvOrder.Rows[i].Cells[2].Text) + 1);
dgvOrder.Rows[i].Cells[3].Text = Convert.ToString(Convert.ToInt32(dgvOrder.Rows[i].Cells[2].Text) * price);
}
}
if (!isExist)
{
DataRow dr = dt.NewRow();
dr["pCode"] = b.ID;
dr["desc"] = description;
dr["qty"] = "1";
dr["price"] = price;
dt.Rows.Add(dr);
dgvOrder.DataSource = dt;
dgvOrder.DataBind();
}
Because I am planning to pass the datatable using the session variable.
Session["orders"] = dt;
Response.Redirect("FinalizeOrder.aspx");
after passing the data, the code is working but only 1 qty for each item is passing.
Can anyone help me in this issue?
The problem is that you reload the DataSource of the GridView only if !isExist. Otherwise you are changing the datatable, but you are not assigning it to the GridView again, so the values are coming from the ViewState.
So this should work:
// update the table
// ...
if (!isExist)
{
// ...
}
// reassign the updated DataTable and DataBind the grid always
dgvOrder.DataSource = dt;
dgvOrder.DataBind();

How can i access value of datalist controls which generated at run time in ASP.NET

The datalist generated code at runtime: how can I access values of the datalist element after page postback?
void CreateDATELIST(Control container)
{
var st = settings.CustomPossition();
foreach (var item in settings.CustomPossition())
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Possition");
dt.Columns.Add("Production");
dt.Columns.Add("dpo");
dt.Columns.Add("WorkDay");
DataRow dr;
foreach (var users in item.Users)
{
dr = dt.NewRow();
dr["Name"] = users.Name;
dr["Possition"] = users.Position.Name;
dr["Production"] = users.DailyGoalAmount * (double)(users.WorkDays / 12;
dr["dpo"] = users.DailyGoalAmount;
dr["WorkDay"] = users.WorkDays;
dt.Rows.Add(dr);
dt.AcceptChanges();
}
DataList dataList = new DataList();
dataList.ItemTemplate = Page.LoadTemplate("Commnets.ascx");
container.Controls.Add(dataList);
dataList.DataSource = dt;
dataList.DataBind();
}
}
You can just subscribe to DataList's ItemDataBound event.
DataList dataList = new DataList();
dataList.ItemDataBound += dataList_ItemDataBound;
and in event handler:
void dataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
var item = e.Item.DataItem as DataRowView;
}
If you assign Id to your DataList created dynamically like following:
DataList dataList = new DataList();
dataList.ID = "dlstUser";
And then: change control ID in c.FindControl("lblName") with whatever control & ID you have in your template user control and use following code in button click or in whatever event where you want values of your datalist.
DataList dataList = pnlDataList.FindControl("dlstUser") as DataList;
foreach (DataListItem dli in dataList.Items)
{
ControlCollection controls = dli.Controls;
foreach (Control c in controls)
{
Label lblName = c.FindControl("lblName") as Label;
}
}

add boundField to gridview in codebehind file C#

I want to create new gridview in codebehind file asp.net C#.
Exactly I want to add such boundfield to the gridview by c# code:
<asp:BoundField DataField="p_type" HeaderText="type" ItemStyle-Width="70px">
<ItemStyle Width="70px"></ItemStyle>
</asp:BoundField>
I crated new gridview with following code:
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.CellPadding = 4;
GridView1.GridLines= GridLines.None;
GridView1.AutoGenerateColumns = false;
And I want to add new boundField to this gridview.
How to make that with c# code?
this article explain you how implement in c# code a gridview :
http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view
here a sample code to create it:
public partial class _Default : System.Web.UI.Page
{
#region constants
const string NAME = "NAME";
const string ID = "ID";
#endregion
protected void Page_Load(object sender, EventArgs e)
{
loadDynamicGrid();
}
private void loadDynamicGrid()
{
#region Code for preparing the DataTable
//Create an instance of DataTable
DataTable dt = new DataTable();
//Create an ID column for adding to the Datatable
DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));
dcol.AutoIncrement = true;
dt.Columns.Add(dcol);
//Create an ID column for adding to the Datatable
dcol = new DataColumn(NAME, typeof(System.String));
dt.Columns.Add(dcol);
//Now add data for dynamic columns
//As the first column is auto-increment, we do not have to add any thing.
//Let's add some data to the second column.
for (int nIndex = 0; nIndex < 10; nIndex++)
{
//Create a new row
DataRow drow = dt.NewRow();
//Initialize the row data.
drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));
//Add the row to the datatable.
dt.Rows.Add(drow);
}
#endregion
//Iterate through the columns of the datatable to set the data bound field dynamically.
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
GrdDynamic.Columns.Add(bfield);
}
//Initialize the DataSource
GrdDynamic.DataSource = dt;
//Bind the datatable with the GridView.
GrdDynamic.DataBind();
}
}

Bind a multi-dimensional ArrayList to a Gridview

I have a DataGrid of seats available, each with a checkbox to be able to reserve the seat. In the button click event, if the CheckBox is clicked, I am adding the contents of the row to an ArrayList, then adding the ArrayList to a session before redirecting to the confirmation page:
protected void Reserve_Click(object sender, EventArgs e)
{
{
ArrayList seatingArreaList = new ArrayList();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Guid SeatId = (Guid)GridView1.DataKeys[i][0];
CheckBox cbReserve = (CheckBox)GridView1.Rows[i].FindControl("cbReserve");
Label lblSection = (Label)GridView1.Rows[i].FindControl("lblSection");
Label lblRow = (Label)GridView1.Rows[i].FindControl("lblRow");
Label lblPrice = (Label)GridView1.Rows[i].FindControl("lblPrice");
if (cbReserve.Checked)
{
string tempRowInfo = lblSection.Text + "|" + lblRow.Text + "|" + lblPrice.Text;
seatingArreaList.Add(tempRowInfo);
}
}
// Add the selected seats to a session
Session["Seating"] = seatingArreaList;
}
Response.Redirect("Confirm.aspx?concertId=" + Request.QueryString["concertId"]);
}
On the confirmation page, Id like to split this array up and bind it to another gridview in their individual columns.
On the confirmation page, a session exists that has three columns separated with a pipe, I am struggling to split this up and bind it to a confirmation grid.
Please help!
This would probably be easier to just create a DataTable, then add it to the session variable. Once redirected to the confirmation page just bind GridView to the DataTable pulled from the session variable.
protected void Reserve_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Section");
dt.Columns.Add("Row");
dt.Columns.Add("Price");
{
ArrayList seatingArreaList = new ArrayList();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Guid SeatId = (Guid)GridView1.DataKeys[i][0];
CheckBox cbReserve = (CheckBox)GridView1.Rows[i].FindControl("cbReserve");
Label lblSection = (Label)GridView1.Rows[i].FindControl("lblSection");
Label lblRow = (Label)GridView1.Rows[i].FindControl("lblRow");
Label lblPrice = (Label)GridView1.Rows[i].FindControl("lblPrice");
if (cbReserve.Checked)
{
DataRow dr = dt.NewRow();
dr["Section"] = lblSection.Text;
dr["Row"] = lblRow.Text;
dr["Price"] = lblPrice.Text;
dt.Rows.Add(dr);
}
}
// Add the selected seats to a session
Session["Seating"] = dt;
}
Response.Redirect("Confirm.aspx?concertId=" + Request.QueryString["concertId"]);
}
var q = from dto in seatingArreaList
let z = dto.Split("|".ToCharArray())
select z;
and then just bing q to the grid.

Resources