How can i access value of datalist controls which generated at run time in ASP.NET - 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;
}
}

Related

Programmatically add OnRowDelete to a GridView

I'm programatically generating GridViews, each GridView has a CommandField with a delete button. How do I programatically add OnDeletingRow so that a function is called when the delete button with the GridView is clicked?
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.ID = "GridView_" + selectedId;
gv.DataKeyNames = new string[] {"id"};
gv.AllowPaging = false;
gv.CellPadding = 3;
gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);
CommandField commandfieldDeallocate = new CommandField();
commandfieldDeallocate.HeaderText = "DELETE NUMBER";
commandfieldDeallocate.ShowDeleteButton = true;
commandfieldDeallocate.DeleteText = "DELETE";
gv.Columns.Add(commandfieldDeallocate);
In C#, you can do it this way:
gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);
void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// Perform deletion
}

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.";
}

Reading selected ITEMS from Dynamically Created ListBox in asp.net

i have created ListBox's Dynamically in a panel and i want to read the selected item from the Listbox created dynamically . below is the code that i used to create the Dynamic Listbox. can anyone please help me how to get the dynamically created listbox and then read the item selected. 'protected void GotoReport_Click(object sender, ImageClickEventArgs e)
{
foreach (TreeNode tndim in tvCubedef.CheckedNodes)
{
lbFilter.Items.Add(tndim.Text);
}
foreach (ListItem item in lbFilter.Items)
{
item.Selected = true;
}
panFilter.Controls.Clear();
connstr2 = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
conn2.ConnectionString = connstr2;
conn2.Open();
CubeCollection CubeList = conn2.Cubes;
string cb = ddlCubeList.SelectedItem.Text;
foreach (ListItem li in lbFilter.Items)
{
ListBox listb = new ListBox();
ListItem Memlist = new ListItem();
listb.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple;
listb.Height = 150;
listb.Width = 250;
string Repl1 = li.Value.Replace("[", "");
string Repl2 = Repl1.Replace("]", "");
string[] DimMember = Repl2.Split('.');
foreach (Member dimem in CubeList[cb].Dimensions[DimMember[0]].Hierarchies[DimMember[1]].Levels[DimMember[2]].GetMembers())
{
Memlist.Text = dimem.Name;
listb.Items.Add(Memlist);
panFilter.Controls.Add(listb);
}
}
} '
You need to add the event-handler dynamically:
listb.SelectedIndexChanged += new EventHandler(listb_SelectedIndexChanged);
Of course you also need to provide this method:
protected void listb_SelectedIndexChanged(Object sender, EventArgs e)
{
ListBox listb = (ListBox) sender;
}
Are you recreating this ListBox on every postback (as you should) in page_load at the latest and with same ID as before?

create custom gridview template fields for a List<>

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

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