i created gridview dynamically,
which consists of Textboxes and buttonfield, on row command event of the gridview i want to access the content of textbox.
i am not able to access the textbox
here is my code
protected void FillGridListTollCollection()
{
TollCollectionBLLC tollcollectionBLLC = new TollCollectionBLLC();
dataTable = tollcollectionBLLC.GetTollCollectionDetailsBLLC(187, 1, 1, "10/10/2011");
//put the gridview into the placeholder to get the values of textboxes in gridview
PlaceHolder1.Controls.Add(GridListTollColletion);
foreach (DataColumn col in dataTable.Columns)
{
if (col.ToString() == "TollCollID")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollCollID";
bField.DataField = "TollCollID";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollAmtApplicable")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollAmtApplicable";
bField.DataField = "TollAmtApplicable";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollCollDesc")
{
BoundField bField = new BoundField();
bField.HeaderText = "Transaction Types";
bField.DataField = "TollCollDesc";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "Total")
{
BoundField bField = new BoundField();
bField.HeaderText = "Total";
bField.DataField = "Total";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString().Contains("Rate"))
{
BoundField bField = new BoundField();
bField.HeaderText = col.ToString();
bField.DataField = col.ToString();
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
//Declare the bound field and allocate memory for the bound field.
TemplateField tfield = new TemplateField();
//Initalize the DataField value.
tfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
tfield.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
tfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.ItemStyle.VerticalAlign = VerticalAlign.Middle;
//Initialize the HeaderText field value.
tfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
GridListTollColletion.Columns.Add(tfield);
}
protected void GridListTollColletion_RowCommand(object sender, GridViewCommandEventArgs e)
{
int tempCarCount = 0;
// here i am getting exception
int.TryParse( ( (TextBox)GridListTollColletion.Rows[Convert.ToInt32(e.CommandArgument)].Cells[Convert.ToInt32(e.CommandArgument)].Controls[3]).Text , out tempCarCount);
}
public class GridViewTemplate : ITemplate
{
//A variable to hold the type of ListItemType.
ListItemType _templateType;
//A variable to hold the column name.
string _columnName;
//Constructor where we define the template type and column name.
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;
//Stores the column name.
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label(); //Allocates the new label object.
lbl.Text = _columnName; //Assigns the name of the column in the lable.
container.Controls.Add(lbl); //Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox(); //Allocates the new text box object.
tb1.Width = 60;
tb1.Height = 22;
tb1.MaxLength = 50;
tb1.ID = "v";
//Creates a column with size 4.
tb1.DataBinding += new EventHandler(tb1_DataBinding); //Attaches the data binding event.
tb1.Columns = 7;
container.Controls.Add(tb1);
//Adds the newly created textbox to the container.
break;
case ListItemType.EditItem:
//As, I am not using any EditItem, I didnot added any code here.
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
public IOrderedDictionary ExtractValues(Control container)
{
OrderedDictionary dict = new OrderedDictionary();
if (_templateType == ListItemType.Item)
{ string value = ((TextBox)container.FindControl("tb1" + _columnName)).Text;
dict.Add(_columnName, value); }
return dict;
}
void tb1_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();
}
}
public GridViewTemplate()
{
//
// TODO: Add constructor logic here
//
}
}
The template is applied statically. So, you wont be able to access the control as you are trying to do.
Try using -
var textbox = GridListTollColletion.FindControl(<yourtextbox>);
Is it not convenient if you bind these added controls on GridView.RowDataBound event.
Check this BindData to ITemplate for GridView in code behind
If you are following this MSDN Article How To: Create ASP.NET Web Server Control Templates Dynamically to take idea about this then check this code snippet.
static void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
RepeaterItem ri = (RepeaterItem)ph.NamingContainer;
Int32 item1Value = (Int32)DataBinder.Eval(ri.DataItem, "CategoryID");
String item2Value = (String)DataBinder.Eval(ri.DataItem, "CategoryName");
((Label)ph.FindControl("item1")).Text = item1Value.ToString();
((Label)ph.FindControl("item2")).Text = item2Value;
}
It have Item_DataBinding a static method. you are setting up this stuff statically, so check this article to improve your code.
In Edit Template i suggest you to use RowBound Event to handle for these template controls.. there you can easily access them.
Related
I have dynamic forms that are build from xml. I can generate the form but I can't get new values from it. I get only the old values that were generated. I would like to update values that are diffrent from old. I think the problem is that I override the new values on page_init with old ones?
This is a dropbox link to my UI for better understanding what I want to achive : https://www.dropbox.com/s/nacs9ohgjxefft9/FormView.png?dl=0#
public sealed class FormViewEditTemplate : IBindableTemplate
{
public FormViewEditTemplate(ListItemType type, mmXMLdoc.mmXMLdoc editXmlForm)
{
templateType = type;
_editXmlForm = editXmlForm;
}
//This method provides a way to insert an instance of text and controls into the specified container.
void ITemplate.InstantiateIn(Control container)
{
tabela = new Table();
tabs = new TabContainer();
tapPanel = new TabPanel();
row = new TableRow();
switch (templateType)
{
case ListItemType.EditItem:
List<XmlElement> Controls = _editXmlForm.getNodCollection("//Tabs");
if (Controls.Count > 0)
{
//pridobimo tabe za formo
foreach (XmlElement ctrlItem in Controls)
{
var ControlsItems = _editXmlForm.getNodCollection("./Controls", "Control", -1, ctrlItem);
tabela = new Table();
tapPanel = new TabPanel();
tapPanel.ID = Guid.NewGuid().ToString();
tapPanel.HeaderText = ctrlItem.GetAttribute("name").ToString();
//pridobimo podatke za formo
//var controls1 = ctrlItem.SelectNodes("//Controls");
foreach (XmlElement ctrl in ControlsItems)
{
string name = _editXmlForm.gStr("./#name", -1, ctrl) + Guid.NewGuid().ToString();
string label = _editXmlForm.gStr("./#label", -1, ctrl);
string width = _editXmlForm.gStr("./#width", -1, ctrl);
string type = _editXmlForm.gStr("./#type", -1, ctrl);
string value = String.Empty;
string helpnote = _editXmlForm.gStr("./HelpNote", -1, ctrl);
string boundfield = _editXmlForm.gStr("./BoundField", -1, ctrl);
row = new TableRow();
TableCell cell = new TableCell();
switch (type)
{
case "TextBox":
//The TemplateField allows for a mix of HTML markup, Web controls, and data-binding syntax.
Label lbl_item = new Label();
lbl_item.Font.Bold = true;
lbl_item.Text = label + ": ";
cell = new TableCell();
cell.Controls.Add(lbl_item);
row.Controls.Add(cell);
TextBox txt_item = new TextBox();
txt_item.ID = boundfield;
txt_item.Text = boundfield;
txt_item.DataBinding += new EventHandler(txt_DataBind);
cell = new TableCell();
cell.Controls.Add(txt_item);
row.Controls.Add(cell);
break;
case "CheckBox":
lbl_item = new Label();
lbl_item.Font.Bold = true;
lbl_item.Text = label + "<br/>";
//The BoundField displays the value of specified DataSource field as text.
BoundField bfield = new BoundField();
bfield.HeaderText = label;
bfield.DataField = boundfield;
break;
default:
break;
}
tabela.Controls.Add(row);
}
tapPanel.Controls.Add(tabela);
tabs.Controls.Add(tapPanel);
}
}
break;
case ListItemType.Footer:
Button saveButton = new Button();
saveButton.Command += new CommandEventHandler(SaveButton_Command);
saveButton.CommandName = "Update";
saveButton.Text = "Save";
saveButton.ID = "EditButton";
container.Controls.Add(saveButton);
break;
}
container.Controls.Add(tabs);
}
IOrderedDictionary IBindableTemplate.ExtractValues(Control container)
{
OrderedDictionary dict = new OrderedDictionary();
List<XmlElement> Controls = _editXmlForm.getNodCollection("//Tabs");
if (Controls.Count > 0)
{
//pridobimo tabe za formo
foreach (XmlElement ctrlItem in Controls)
{
var ControlsItems = _editXmlForm.getNodCollection("./Controls", "Control", -1, ctrlItem);
foreach (XmlElement ctrl in ControlsItems)
{
string type = _editXmlForm.gStr("./#type", -1, ctrl);
string boundfield = _editXmlForm.gStr("./BoundField", -1, ctrl);
switch (type)
{
case "TextBox":
TextBox tb = (TextBox)FindControlRecursive(container, boundfield);
if (tb != null)
dict[boundfield] = tb.Text;
break;
case "Label":
Label lb = (Label)FindControlRecursive(container, boundfield);
if (lb != null)
dict[boundfield] = lb.Text;
break;
case "CheckBox":
CheckBox cb = (CheckBox)FindControlRecursive(container, boundfield);
if (cb != null)
dict[boundfield] = cb.Checked;
break;
case "DropDown":
DropDownList ddl = (DropDownList)FindControlRecursive(container, boundfield);
if (ddl != null)
dict[boundfield] = ddl.SelectedValue;
break;
default:
break;
}
}
}
}
return dict;
}
private Control FindControlRecursive(Control ctlRoot, string sControlId)
{
// if this control is the one we are looking for, break from the recursion
// and return the control.
if (ctlRoot.ID == sControlId)
{
return ctlRoot;
}
// loop the child controls of this parent control and call recursively.
foreach (Control ctl in ctlRoot.Controls)
{
Control ctlFound = FindControlRecursive(ctl, sControlId);
// if we found the control, return it.
if (ctlFound != null)
{
return ctlFound;
}
}
// we never found the control so just return null.
return null;
}
I call this in Page_init
protected void Page_Init(object sender, EventArgs e)
{
FormViewEdit.HeaderTemplate = new FormViewEditTemplate(ListItemType.Header, editXmlForm);
FormViewEdit.EditItemTemplate = new FormViewEditTemplate(ListItemType.EditItem, editXmlForm);
FormViewEdit.FooterTemplate = new FormViewEditTemplate(ListItemType.Footer, editXmlForm);
FormViewEdit.ItemUpdating += new FormViewUpdateEventHandler(FormView1_ItemUpdating);
EditFormView.SelectCommand = "SELECT * FROM " + UniqueTable + " WHERE " + PrimaryKey + "=" + ident;
EditFormView.DataBind();
}
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
//TODO get all new values and make query string.
EditFormView.UpdateCommand = "UPDATE " + UniqueTable + " SET bla_Opis='" + e.NewValues["bla_Opis"] + "' WHERE " + PrimaryKey + "=" + ident;
EditFormView.Update();
EditFormView.DataBind();
}
I found the problem. I used randomly generated id for tap panel therfore I believe the the two way binding didnt work on post back. On every postback I got new id and the old data didnt find control to bind the new values.
tapPanel.ID = Guid.NewGuid().ToString();
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
}
my datatable formed as follows
DataTable dtFinalData = new DataTable();
//Adding columns for BR details
dtFinalData.Columns.Add("SupId", typeof(string));
dtFinalData.Columns.Add("SupName", typeof(string));
DateTime dt = DateTime.Today;
int num = DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month);
//--> adding columns for date part (1-31)
for (int i = 1; i < num + 1; i++)
{
dtFinalData.Columns.Add(i.ToString(), typeof(bool));
}
//<-- adding columns for date part (1-31)
#endregion
#region Fill dtFinalData
//--> Looping each BR from tblBrList
foreach (DataRow BrRow in dtBrList.Rows)
{
DataRow dr = dtFinalData.NewRow();
int SupId = Convert.ToInt32(BrRow[0]); //retrieve BR ID from dtBrList
String supName = BrRow[1].ToString(); //retreive Supervisor name from dtBrList
dr["SupId"] = SupId.ToString();
dr["SupName"] = supName;
for (int i = 1; i < num + 1; i++)
{
DateTime dtRunningDate = new DateTime(2013, 5, i);
//select BR_SUP_CODE,
DataRow[] drAttendance = dtAttendance.Select("BR_SUP_CODE=" + SupId + " AND SMS_DATE=#" + dtRunningDate + "#", string.Empty);
if (drAttendance.Length == 1)
{
//CheckBox chkbx = new CheckBox();
//chkbx.Checked = true;
dr[i.ToString()] = true;
}
else
{
//CheckBox chkbx = new CheckBox();
//chkbx.Checked = false;
dr[i.ToString()] = false;
}
}
dtFinalData.Rows.Add(dr);
}
//<-- Looping each BR from tblBrList
#endregion
GridView1.DataSource = dtFinalData;
GridView1.DataBind();
Now i want to add checked image in place of true and unchecked image in place of false.how to bind grid view dynamically such that in place of disable check box i want to insert two types of image?
Your DataTable part is fine and continue to add the True/False text as per the logic. Now you should handle the GridView part. So, define an event handler for the OnRowDataBound event of GridView.
In this event only, check for the Text property of the cells, and if True/False, clear the cells and add the required image.
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" ... />
And your event handler will have code as below:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Image chkImage = new Image();
chkImage.ImageUrl="~/images/Checked.png";
Image UnchkImage = new Image();
UnchkImage.ImageUrl = "~/images/UnChecked.png";
if (e.Row.RowType == DataControlRowType.DataRow)
{
// We will start from 3rd cell because the first 2 cells are
// for SupID & SupName, where we don't need to place images
for (int cellIndex = 2; cellIndex < GridView1.Columns.Count; cells++)
{
// Add Checked Image when cell text is true
if (e.Row.Cells[cellIndex].Text == "true")
{
// clear the cell and add only the image
e.Row.Cells[cellIndex].Controls.Clear();
e.Row.Cells[cellIndex].Controls.Add(chkImage);
}
// Add Unchecked Image when cell text is false
if (e.Row.Cells[cellIndex].Text == "false")
{
// clear the cell and add only the image
e.Row.Cells[cellIndex].Controls.Clear();
e.Row.Cells[cellIndex].Controls.Add(unchkImage);
}
}
}
}
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();
}
}
Hi i added template field dynamically to gridview by implementing ITemplate interface.
The template field contains some controls like label and textboxes. how do i get these controls in row databound event.
I am not able to get when i do gridviewrow.findcontrol("id") as i do normally when we add templatefield from aspx page.
The way i added template field is like this
public class CustomGridViewColumn : ITemplate
{
ListItemType _liType;
string _columnName;
public CustomGridViewColumn(ListItemType type, string column)
{
_liType = type;
_columnName = column;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_liType)
{
case ListItemType.Header:
Label lblHeader = new Label();
lblHeader.Text = _columnName;
container.Controls.Add(lblHeader);
break;
case ListItemType.Item:
Label lblItem = new Label();
lblItem.DataBinding += new EventHandler(lbl_DataBinding);
lblItem.ID = "lbl" + _columnName;
lblItem.ClientIDMode = ClientIDMode.Predictable;
container.Controls.Add(lblItem);
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(ddl_DataBinding);
ddl.ID = "ddl" + _columnName;
ddl.Visible = false;
container.Controls.Add(ddl);
break;
}
}
}
Now i want access the label and dropdown which i have added using this code.
when i do gridviewrow.findcontrol("id") i am not getting them.
Can any one please help me.
I am geeting when i go through all the rows and try to find but
i have a check box in a row when i select it all labels should diappear and ddls dhould appear
for this i am using the follwoing code.
protected void chkEdit_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkEditTest = (CheckBox)sender;
GridViewRow grow = (GridViewRow)chkEditTest.NamingContainer;
DropDownList ddl = (DropDownList)grow.FindControl("ddl");
Label lbl= (Label)grow.FindControl("lbl");
}
when i do this i am not able to get the controls.
it seems like controls are disapppearing on postback..
This is what I came up with and I can able to get the control reference in the code behind.
public class CustomGridViewColumn : ITemplate
{
ListItemType _liType; string _columnName;
public CustomGridViewColumn(ListItemType type, string column)
{
_liType = type;
_columnName = column;
}
void ITemplate.InstantiateIn(Control container)
{
switch (_liType)
{
case ListItemType.Header:
Label lblHeader = new Label();
lblHeader.Text = _columnName;
container.Controls.Add(lblHeader);
break;
case ListItemType.Item:
Label lblItem = new Label();
lblItem.DataBinding += new EventHandler(lblItem_DataBinding);
lblItem.ID = "lbl" + _columnName;
lblItem.ClientIDMode = ClientIDMode.Predictable;
container.Controls.Add(lblItem);
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(ddl_DataBinding);
ddl.ID = "ddl" + _columnName;
ddl.Visible = false;
ddl.DataSource = new string[] { "Hello", "World" };
container.Controls.Add(ddl);
break;
}
}
void ddl_DataBinding(object sender, EventArgs e)
{
}
void lblItem_DataBinding(object sender, EventArgs e)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
DataRow oItem = dt.NewRow();
oItem[0] = "Deepu";
dt.Rows.Add(oItem);
oItem = dt.NewRow();
oItem[0] = "MI";
dt.Rows.Add(oItem);
GridView gv = new GridView();
gv.ID = "myGridView";
gv.AutoGenerateColumns = false;
BoundField nameColumn = new BoundField();
nameColumn.DataField = "Name";
nameColumn.HeaderText = "Name";
gv.Columns.Add(nameColumn);
TemplateField TmpCol = new TemplateField();
TmpCol.HeaderText = "Template Column";
gv.Columns.Add(TmpCol);
TmpCol.ItemTemplate = new CustomGridViewColumn(ListItemType.Item, "TEST");
gv.DataSource = dt;
gv.DataBind();
Form.Controls.Add(gv);
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView gv = Form.FindControl("myGridView") as GridView;
foreach (GridViewRow item in gv.Rows)
{
var ddl = item.FindControl("ddlTest") as DropDownList;
if (ddl != null)
{
ddl.Visible = true;
}
var lbl = item.FindControl("lbl") as Label;
if (lbl != null)
{
lbl.Text = "hello";
}
}
}
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
Thanks
Deepu
Can you try using row index of GRIDVIEW control
var rowIndex = int.Parse(e.CommandArgument)
GridView1.Rows[rowIndex].FindControl("id")
Also refer
http://forums.asp.net/t/998368.aspx/1
http://www.codeproject.com/Articles/12021/Accessing-the-different-controls-inside-a-GridView
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.aspx
Thanks
Deepu