how to get checkbox is check in gridview OnRowEditing - asp.net

if anyone can help me, I have problems with gridview, when I use OnRowEditing and OnRowDeleting and inside asp: TemplateField, ItemTemplate I am using a checkbox, when checked the checkbox in checkbox.checked value is never true,
below is my C # script
<asp: Button ID = "Button1" runat = "server" BackColor = "# EFF1F1" BorderStyle = "None"
onclick = "Button1_Click" Text = "Submit Work Program" />
<asp: GridView ID = "GV_program" runat = "server" AutoGenerateColumns = "False"
Its DataKeyNames = "KD_BIDANG" Width = "100%" AutoGenerateEditButton = "True"
AutoGenerateDeleteButton = "true" OnRowEditing = "GV_program_RowEditing"
OnRowDeleting = "GV_program_RowDeleting" OnRowDataBound = "GV_kegiatan_RowDataBound"
BackColor = "White" EmptyDataText = "No Data Activity" AllowPaging = "True">
<EmptyDataRowStyle BackColor="#FF9900" />
<Columns> <asp:TemplateField HeaderStyle-Width="20px"> <ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" /> </ItemTemplate> </asp:TemplateField>
</ Columns> </ asp: GridView>
C #
protected void Button1_Click (object sender, EventArgs e)
{
foreach (GridViewRow row in GV_program.Rows)
{
if (((CheckBox) row.FindControl ("cbSelect")). Checked)
{
// Delete something (never get here)
}
}
}

take it one step at a time until you get it working......
Try this:
/* put this value at the "class level" */
public static readonly int GRID_VIEW_COLUMN_ORDINAL_chkBoxSELECT = 3; /* Your number may be different, its the ordinal column number. A static readonly or const value makes your code more readable IMHO */
/*Then in your method */
if (null != this.GV_program)
{
Control cntl = null;
foreach (GridViewRow gvr in this.GV_program.Rows)
{
cntl = gvr.Cells[GRID_VIEW_COLUMN_ORDINAL_chkBoxSELECT].FindControl("cbSelect");
CheckBox cbIsApproved = cntl as CheckBox;
if (null != cbIsApproved)
{
bool myValue = cbIsApproved.Checked;
}
}
}
I just ran this code, and it worked for me.
protected void imgbutSave_Click(object sender, ImageClickEventArgs e)
{
if (null != this.gvMain)
{
Control cntl = null;
string finalMsg = string.Empty;
int counter = 0;
StringBuilder sb = new StringBuilder();
foreach (GridViewRow gvr in this.gvMain.Rows)
{
counter++;
cntl = gvr.Cells[GRID_VIEW_COLUMN_ORDINAL_chkBoxIsApproved].FindControl("chkBoxIsApproved");
CheckBox cbIsApproved = cntl as CheckBox;
if (null != cbIsApproved)
{
sb.Append(string.Format("Row '{0}' (chkBoxIsApproved.Checked) = '{1}'", counter, cbIsApproved.Checked) + System.Environment.NewLine);
}
}
finalMsg = sb.ToString();
}
}
and my aspx code
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBoxIsApproved" runat="server" Checked='<%#Eval("IsApproved")%>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
My StringBuilder had all of the checkboxes on my page, with the correct .Checked value.

Related

set text to textbox based on selected value from dropdownlist in gridview asp net

I have one Dropdown and one textBox in my gridview.
gridview contains some subject name and in database there is fees for particular
subject. I want to show that Fees into textbox on every value selected for dropdown.
i have done the same functionality which gives exact output what i want but not immediately after selection of subject, it gives value on button click.
may be i have done something wrong but not found exact solution please help.
ASPX code :
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="Gridview1_RowDataBound" CssClass="EU_DataTable">
<Columns>
<asp:TemplateField HeaderText="Program Name">
<ItemTemplate>
<asp:DropDownList ID="ddl_ProgList" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="ddl_ProgList_SelectedIndexChanged" ControlStyle-Width="160px">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Fees">
<ItemTemplate>
<asp:TextBox ID="txt_fees" runat="server" ControlStyle-Width="75px"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind :
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Control ctrl = e.Row.FindControl("ddl_ProgList");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
//SqlConnection conn = new SqlConnection(connStr);
clsProg_TB objprg = new clsProg_TB();
objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
DataSet ds = clsUserLogicLayer.LoadPrograms(objprg);
dd.DataTextField = "prg_Name";
dd.DataValueField = "prg_Name";
dd.DataSource = ds.Tables[0];
dd.DataBind();
}
}
}
protected void ddl_ProgList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
Control ctrl = row.FindControl("ddl_ProgList") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
TextBox txt2 = row.FindControl("txt_fees") as TextBox;
clsProg_TB objprg = new clsProg_TB();
objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
objprg.Prg_Name = ddl1.SelectedItem.ToString();
DataSet ds = clsUserLogicLayer.getProgFees(objprg);
if (ds.Tables[0].Rows.Count != 0)
{
txt2.Text = ds.Tables[0].Rows[0][0].ToString();
}
}
}
}
}
You can try to update Row and the bind the gridview again. You also need to set GridView.SetEditRow() before starting editing. Another way is to update your dataTable and bind it again.
protected void ddl_ProgList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
foreach (GridViewRow row in Gridview1.Rows)
{
GridView.SetEditRow(row.RowIndex);
Control ctrl = row.FindControl("ddl_ProgList") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
TextBox txt2 = row.FindControl("txt_fees") as TextBox;
clsProg_TB objprg = new clsProg_TB();
objprg.Center_Code = ddl_centerCode.SelectedItem.ToString();
objprg.Prg_Name = ddl1.SelectedItem.ToString();
DataSet ds = clsUserLogicLayer.getProgFees(objprg);
if (ds.Tables[0].Rows.Count != 0)
{
txt2.Text = ds.Tables[0].Rows[0][0].ToString();
}
}
}
Gridview1.UpdateRow(row.RowIndex, false);
}
Gridview1.DataBind();
}

Checkbox inside gridview in asp.net

I am using checkbox in a gridview:
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkhdr" runat="server" AutoPostBack="true" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox CssClass="gridrownormal3" ID="chkChild" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Button click for binding grid:
protected void Button1_Click(object sender, EventArgs e)
{
/*
* Clear All Data in Grid By Calling Empty_GridView
* */
if (this.IsValid)
{
Empty_GridView(grdDocList_Summary);
List<SearchEngineEO> doc = Docs;
var query18 = (from c in doc
select new { c.DocNO, c.DocType, c.Title, c.Padid,
c.PublisherName, c.PublishedDate,
c.Rade }).Distinct().ToList();
grdDocList_Summary.DataSource = query18;
grdDocList_Summary.DataBind();
}
}
I select the checkbox at run time, I want to show some details of these rows.
I use this code:
for (int i = 0; i < grdDocList_Summary.Rows.Count; i++)
{
GridViewRow row = grdDocList_Summary.Rows[i];
bool isChecked = ((CheckBox)row.FindControl("chkChild")).Checked;
if(isChecked)
{
String str = row.Cells[1].Text;
DocNos.Add(str);
}
}
Suppose I have 10 rows in grdDocList_Summary. When I select one checkbox, for all iteration of for above variable ischecked is true. Why does this happen?

Getting values from textbox in the repeater in button click event

I have a TextBox in a repeater that is populated from the database in the ItemDataBound event. When I tried to get the text inside the TextBox in a Button_Click event I found the TextBox.Text empty. How can I get the Text?
foreach (RepeaterItem repeated in repEdit.Items)
{
DropDownList drp = (DropDownList)FindControlRecursive(repeated, "drpdown");
TextBox txt = (TextBox)FindControlRecursive(repeated, "txt");
CheckBox chk = (CheckBox)FindControlRecursive(repeated, "chk");
if (drp != null && !string.IsNullOrEmpty(drp.Attributes["ID"]))
{
loc.GetType().GetProperty(drp.Attributes["ID"].Split('#')[0] + "ID").SetValue(loc, int.Parse(drp.SelectedValue), null);
}
if (txt != null && !string.IsNullOrEmpty(txt.Attributes["ID"]))
{
if (txt.Attributes["ID"].Contains("#int"))
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, int.Parse(txt.Text), null);
}
else if (txt.Attributes["ID"].Contains("#decimal"))
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, decimal.Parse(txt.Text), null);
}
else
{
loc.GetType().GetProperty(txt.Attributes["ID"].Split('#')[0]).SetValue(loc, txt.Text, null);
}
}
if (chk!=null && !string.IsNullOrEmpty(chk.Attributes["ID"]))
{
loc.GetType().GetProperty(chk.Attributes["ID"].Split('#')[0]).SetValue(loc, chk.Checked, null);
}
}
HTML
<asp:Repeater ID="repEdit" runat="server" OnItemDataBound="repEdit_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Visible="false"></asp:Label>
<asp:TextBox ID="txt" runat="server" Visible="false"></asp:TextBox>
<asp:CheckBox ID="chk" runat="server" Visible="false" />
<asp:DropDownList ID="drpdown" runat="server" Visible="false">
</asp:DropDownList>
<br />
</ItemTemplate>
</asp:Repeater>
Here is the itemdatabound event
protected void repEdit_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Label name = e.Item.FindControl("lblName") as Label;
TextBox text = e.Item.FindControl("txt") as TextBox;
CheckBox chk = e.Item.FindControl("chk") as CheckBox;
DropDownList drp = e.Item.FindControl("drpdown") as DropDownList;
Button but = e.Item.FindControl("butEdit") as Button;
//butEdit.Visible = true;
if (but != null)
{
but.Visible = true;
}
if (e.Item.ItemType == ListItemType.Item)
{
KeyValuePair<string, Dictionary<int, string>> kvp = (KeyValuePair<string, Dictionary<int, string>>)e.Item.DataItem;
if (name != null)
{
if (kvp.Key.Contains("#datetime"))
{
return;
}
name.Visible = true;
name.Text = kvp.Key.Split('#')[0].ToString();
}
if (kvp.Key.Contains("#int") || kvp.Key.Contains("#decimal"))
{
text.Visible = true;
text.ID = kvp.Key;
text.EnableViewState = true;
text.Attributes["ID"] = kvp.Key;
text.Text = kvp.Value[0].ToString();
if (kvp.Key.Split('#')[0] == "ID")
{
text.Enabled = false;
}
}
Here is your Repeater. It has a PlaceHolder and Button.
<asp:Repeater ID="rpNotifications" runat="server"
OnItemDataBound="rpNotifications_ItemDataBound">
<ItemTemplate>
<asp:PlaceHolder ID="commentHolder" runat="server"></asp:PlaceHolder>
<asp:Button runat="server" ID="btnComment"
Text="Comment" CssClass="btn blue"
OnClick="btnComment_Click" CommandArgument='<%# Eval("id") %>' />
</ItemTemplate>
</asp:Repeater>
The button has the command argument set as the Id of the data I am binding to it.
Next here is where you need to Bind your Repeater. If you don't Bind it in the Page_Init the resulting values in the dynamically created controls will be lost.
protected void Page_Init(object sender, EventArgs e)
{
rpNotifications.DataSource = {datasource-here}
rpNotifications.DataBind();
}
And here is why (Image from: http://msdn.microsoft.com/en-us/library/ms972976.aspx)
Dynamically Create Control on ItemDataBound
You will need to add the textbox to the placeholder as this is the only way to dynamically assign an ID to the control.
protected void rpNotifications_ItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem)
{
Common.Models.Item item = (Common.Models.Item)e.Item.DataItem;
// Create new Control
TextBox txtComment = new TextBox();
txtComment.ID = String.Format("txtComment{0}", item.id.ToString());
// Ensure static so you can reference it by Id
txtComment.ClientIDMode = System.Web.UI.ClientIDMode.Static;
// Add control to placeholder
e.Item.FindControl("commentHolder").Controls.Add(txtComment);
}
}
Get Value On Button Click
Now you need to create the event handler for the button and get the resulting value
protected void btnComment_Click(object sender, EventArgs e)
{
// This is the ID I put in the CommandArgument
Guid id = new Guid(((Button)sender).CommandArgument);
String comment = String.Empty;
// Loop through the repeaterItems to find your control
foreach (RepeaterItem item in rpNotifications.Controls)
{
Control ctl = item.FindControl(
String.Format("txtComment{0}", id.ToString()));
if (ctl != null)
{
comment = ((TextBox)ctl).Text;
break;
}
}
}
Try to get ASP.Net controls using below code
DropDownList drp = (DropDownList)repeated.FindControl("drpdown");
TextBox txt = (TextBox)repeated.FindControl("txt");
CheckBox chk = (CheckBox)repeated.FindControl("chk");
Then you can get values from there respective properties.

RadioButtonList Postback Issues

Environment: ASP NET 2.0 - Production Server does not have Ajax Control Toolkit so no real Control toolkit to use here.
3 RadioButtons List:
List one loads, after postback, the item from list one is used to select a Lab value.
Once a lab value is selected a 3rd radiobuttonlist will populate. There are some textboxes but they are not shown in example. The textboxes postback themselves on changes. If both textboxes are
not empty, a record is created for the session.
Now if the 3rd radiobuttonlist is changed from the default a series of 3 hidden user controls appear which represent 3 levels of reasons for the change ( child/parent records in database ).
The problem I am having is when I select a different item on the radiobuttonlist the radiobutton 3 OnSelectedIndex is firing after my user controls fire. My user controls need the value of the 3rd list to go to the database and get the correct set of records associated with the lab.
The problem is because the last radiobuttonlist is not processed until after the web controls loads, the code to mount the user controls never happens.
Here is the basic HTML code:
<asp:RadioButtonList ID="rdoLab" runat="server" OnSelectedIndexChanged="rdoLab_OnSelectedIndexChange">
</asp:RadioButtonList>
<asp:TextBox ID="textbox1" runat="server" OnTextChanged="TextBoxProcess" />
<asp:TextBox ID="textbox2" runat="server" OnTextChanged="TextBoxProcess" />
<asp:RadioButtonList ID="rdoPrimary" RepeatColumns="3" OnSelectedIndexChanged="rdoPrimary_OnSelectedIndexChanged" runat="server" ToolTip="Select Normal, Hypo or Hyper - Normal is default value." AutoPostBack="True" >
<asp:ListItem Value="3" Text="Normal" Selected="true"/>
<asp:ListItem Value="1" Text="Hypo" />
<asp:ListItem Value="2" Text="Hyper" />
</asp:RadioButtonList>
<asp:Panel ID="UpdLab" runat="server" Visible="true" EnableViewState="true">
<asp:Table ID="tblAdmin" runat="server">
<asp:TableRow>
<asp:TableCell runat="server" id="tblCell1" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab1" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell2" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab2" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell3" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab3" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
Here is the page behind:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
GetSessionVars();
if (CommonUI.strTest((string)Session["rdoLabs"]) && CommonUI.strTest((string)Session["rdoPrimary"]) && Convert.ToString(hrdoLabs.Value) == (string)Session["rdoLabs"])
{
divLabLvl.Visible = true;
// Get cboListItems from the web user controls...
Session["ArrLstItems"] = "";
ArrayList ArrLstItems = new ArrayList();
ArrayList GetWuc = GetWUCS();
for (int i = 0; i < GetWuc.Count; i++)
{
Lab wuc = (Lab)GetWuc[i];
CheckBoxList cboItemList = (CheckBoxList)wuc.FindControl("cboItems");
string cboItems = GetCboItemList(cboItemList);
HiddenField hcboItems = (HiddenField)wuc.FindControl("hcboItems");
}
Session["ArrLstItems"] = (ArrayList)ArrLstItems;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DbDataReader ddrGrp = rdoGroups();
if (ddrGrp.HasRows)
{
rdoGroup.DataSource = ddrGrp;
rdoGroup.DataBind();
}
ddrGrp.Close();
}
else
{
DbDataReader ddrLab = rdoUserLabs();
if (ddrLab.HasRows)
{
rdoLabs.DataSource = ddrLab;
rdoLabs.DataBind();
if (CommonUI.strTest((string)Session["rdoLabs"]))
{
if (Convert.ToInt32(Session["rdoLabs"]) > 0)
{
rdoLabs.SelectedValue = (string)Session["rdoLabs"];
SetLabCss();
}
}
}
ddrLab.Close();
}
}
protected void rdoGroup_OnSelectedIndexChanged(object sender, EventArgs e)
{
//...do some stuff
}
protected void rdoLabs_OnSelectedIndexChanged(object sender, EventArgs e)
{
//... reload
}
protected DbDataReader rdoGroups()
{
int group_type_id = GroupTypeId();
Group grp = new Group();
return grp.GetGroups(group_type_id);
}
protected DbDataReader rdoUserLabs()
{
RadioButtonList rdoGrp = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
int GroupId = Convert.ToInt32(rdoGrp.SelectedValue);
LabAbnormalReasons lar = new LabAbnormalReasons();
return lar.GetLabsList(GroupId);
}
protected void rdoPrimary_OnSelectedIndexChanged(object sender, EventArgs e)
{
Session["Save"] = ((RadioButtonList)sender).ID;
RadioButtonList rdoGroups = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
int UserId = Convert.ToInt32(Session["UserId"]);
int DocId = Convert.ToInt32(Session["DocId"]);
SubmitLab_Data(arrLstItems, arrOthers);
}
protected void GetSessionVars()
{
RadioButtonList rdoGroup = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoPrimary = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoPrimary");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
if (rdoGroup.SelectedIndex != -1)
{
Session["rdoGroup"] = (string)rdoGroup.SelectedValue;
}
if (rdoLabs.SelectedIndex != -1)
{
Session["rdoLabs"] = (string)rdoLabs.SelectedValue;
}
if (rdoPrimary.SelectedIndex != -1)
{
Session["rdoPrimary"] = (string)rdoPrimary.SelectedValue;
}
}
Here is example of user code:
THIS CODE NEVER FIRES BECAUSE the 3rd Button List data is not available here :
protected void Page_Load(object sender, EventArgs e)
{
/////*
//// * lab & Primary have been selected...
//// */
int lvl = SetLvlId();
int par_id = GetParentLvl();
Lab wuc = GetWuc(lvl);
if (wuc != null)
{
if (CommonUI.strTest(Convert.ToString(Session["rdoLabs"])) && CommonUI.strTest(Convert.ToString(Session["rdoPrimary"])))
{
// data in data base for this user, lab, doc identifier...
if (Convert.ToInt32(Session["rdoPrimary"]) > 0
{
// have user hdr data - see if item data is mapped...
// do some stuff here
}
}
}
}
I hope this is clear. I've att
---*--- Since original posting:
added simple javascript/OnDataBound
function Primary(object)
{
alert("Value Clicked :" + object);
}
protected void rdoPrimary_DataBound(object sender, EventArgs e)
{
RadioButtonList rdlPrimary = (RadioButtonList)sender;
foreach (ListItem li in rdlPrimary.Items)
{
li.Attributes.Add("onclick", "javascript:Primary('" + li.Value + "')");
}
}
Store and retrieve the values you want to retain in SaveViewState and LoadViewState methods and see if that works for you? Also look to the earlier and later lifecycle events for handling the logic - Init and OnPreRender. This has worked for me in the past.

asp.net how to add TemplateField programmatically for about 10 dropdownlist

This is my third time asking this question. I am not getting good answers regarding this. I wish I could get some help but I will keep asking this question because its a good question and SO experts should not ignore this...
So I have about 10 dropdownlist controls that I add manually in the DetailsView control manually like follows. I should be able to add this programmatically. Please help and do not ignore...
<asp:DetailsView ID="dvProfile" runat="server"
AutoGenerateRows="False" DataKeyNames="memberid" DataSourceID="SqlDataSource1"
OnPreRender = "_onprerender"
Height="50px" onm="" Width="125px">
<Fields>
<asp:TemplateField HeaderText="Your Gender">
<EditItemTemplate>
<asp:DropDownList ID="ddlGender" runat="server"
DataSourceid="ddlDAGender"
DataTextField="Gender" DataValueField="GenderID"
SelectedValue='<%#Bind("GenderID") %>'
>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate >
<asp:Label Runat="server" Text='<%# Bind("Gender") %>' ID="lblGender"></asp:Label>
</ItemTemplate>
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
=======================================================
Added on 5/3/09
This is what I have so far and I still can not add the drop down list programmatically.
private void PopulateItemTemplate(string luControl)
{
SqlDataSource ds = new SqlDataSource();
ds = (SqlDataSource)FindControl("ddlDAGender");
DataView dvw = new DataView();
DataSourceSelectArguments args = new DataSourceSelectArguments();
dvw = (DataView)ds.Select(args);
DataTable dt = dvw.ToTable();
DetailsView dv = (DetailsView)LoginView2.FindControl("dvProfile");
TemplateField tf = new TemplateField();
tf.HeaderText = "Your Gender";
tf.ItemTemplate = new ProfileItemTemplate("Gender", ListItemType.Item);
tf.EditItemTemplate = new ProfileItemTemplate("Gender", ListItemType.EditItem);
dv.Fields.Add(tf);
}
public class ProfileItemTemplate : ITemplate
{
private string ctlName;
ListItemType _lit;
private string _strDDLName;
private string _strDVField;
private string _strDTField;
private string _strSelectedID;
private DataTable _dt;
public ProfileItemTemplate(string strDDLName,
string strDVField,
string strDTField,
DataTable dt
)
{
_dt = dt;
_strDDLName = strDDLName;
_strDVField = strDVField;
_strDTField = strDTField;
}
public ProfileItemTemplate(string strDDLName,
string strDVField,
string strDTField,
string strSelectedID,
DataTable dt
)
{
_dt = dt;
_strDDLName = strDDLName;
_strDVField = strDVField;
_strDTField = strDTField;
_strSelectedID = strSelectedID;
}
public ProfileItemTemplate(string ControlName, ListItemType lit)
{
ctlName = ControlName;
_lit = lit;
}
public void InstantiateIn(Control container)
{
switch(_lit)
{
case ListItemType.Item :
Label lbl = new Label();
lbl.DataBinding += new EventHandler(this.ddl_DataBinding_item);
container.Controls.Add(lbl);
break;
case ListItemType.EditItem :
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(this.lbl_DataBinding);
container.Controls.Add(ddl);
break;
}
}
private void ddl_DataBinding_item(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ddl.ID = _strDDLName;
ddl.DataSource = _dt;
ddl.DataValueField = _strDVField;
ddl.DataTextField = _strDVField;
}
private void lbl_DataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
lbl.ID = "lblGender";
DropDownList ddl = (DropDownList)sender;
ddl.ID = _strDDLName;
ddl.DataSource = _dt;
ddl.DataValueField = _strDVField;
ddl.DataTextField = _strDTField;
for (int i = 0; i < _dt.Rows.Count; i++)
{
if (_strSelectedID == _dt.Rows[i][_strDVField].ToString())
{
ddl.SelectedIndex = i;
}
}
lbl.Text = ddl.SelectedValue;
}
}
I found this article http://aspalliance.com/1125 about progrmatically creating template field. I hope this can be helpful to solve this problem.
What have you tried? What problem are you having? If you haven't answered these questions before, then it's no surprise that you haven't received a good answer.
Obviously, you have to locate the TemplateFields for which you want to add dropdowns, and you have to set their EditItemTemplate property to an instance of a class that implements ITemplate. That instance will have it's InstantiateIn method called to add controls to a parent control. In this case, this is where you would configure and add your DropDownList.
If this description is not adequate, then you'll have to say in what way it's not adequate, so that I or someone else can answer.

Resources