How to read controls from custom template add on code behind - c#

I need to generate columns which contains checkbox based on data stored in database (this grid can have different number of columns per month)
I've got this code with custom template on my grid view control:
aspx part:
<asp:Button runat="server" ID="bt_save_top" OnClick="bt_save_Click" Text="Save" />
<asp:GridView runat="server" ID="gv_result" AutoGenerateColumns="false" BorderStyle="Solid" BorderWidth="1" RowStyle-BorderWidth="1" RowStyle-BorderStyle="Solid">
</asp:GridView>
*cs :
protected void Page_Load(object sender, EventArgs e)
{
var ds = new DataSet();//getting data from database
var weekDayColumns = GenerateColumns(ds);
foreach (DataControlField dataControlField in weekDayColumns)
{
gv_result_tw.Columns.Add(dataControlField);
}
gv_result_tw.DataSource = ds.Tables[0];
gv_result_tw.DataBind();
}
private DataControlFieldCollection GenerateColumns(DataSet dsTable)
{
var columns = new DataControlFieldCollection();
foreach (DataColumn column in dsTable.Tables[0].Columns)
{
var itemTemplate = new TemplateField
{
HeaderText = column.Caption,
ControlStyle =
{
CssClass = "gv_row"
},
HeaderStyle =
{
CssClass = "gv_row"
},
ItemTemplate = new CustomItemTemplate(ListItemType.Item, column.ColumnName)
};
columns.Add(itemTemplate);
}
return columns;
}
protected void bt_save_Click(object sender, EventArgs e)
{
foreach(var row in gv_result_tw.Rows)
{
var columnNameField = gvr.FindControl("hidden_time") as HiddenField;
// Here i'm getting always null
}
}
CustomItemTemplate.cs
public class CustomItemTemplate : ITemplate
{
private readonly ListItemType _type;
private readonly string _columnName;
public ItemTemplateGenerator(ListItemType t, string columnName)
{
_type = t;
_columnName = columnName;
}
// Override InstantiateIn() method
void ITemplate.InstantiateIn(Control container)
{
switch (_type)
{
case ListItemType.Item:
var visibleCheckbox = new CheckBox
{
ID = $"chb_{_columnName.Replace(":", "_")}_visible"
};
visibleCheckbox.DataBinding += VisibleCheckbox_DataBinding;
var invisibleField = new HiddenField
{
ID = $"chb_{_columnName.Replace(":", "_")}_invisible"
};
var hiddenInput = new HiddenField
{
ID = $"hidden_time",
Value = _columnName
};
container.Controls.Clear();
container.Controls.Add(hiddenInput);
container.Controls.Add(visibleCheckbox);
container.Controls.Add(invisibleField);
break;
}
}
// The DataBinding event of your controls
private void VisibleCheckbox_DataBinding(object sender, EventArgs e)
{
var checkBox = (CheckBox)sender;
var container = (GridViewRow)checkBox.NamingContainer;
var hiddenField = (HiddenField)checkBox.NamingContainer.FindControl($"chb_{_columnName.Replace(":","_")}_invisible");
var bindValue = DataBinder.Eval(container.DataItem, _columnName);
// Adding check in case Column allows null values
if (bindValue != DBNull.Value)
{
hiddenField.Value = bindValue.ToString();
checkBox.Checked = bindValue.ToString() == "1";
}
}
}
So the question is how I should done this "FindControl" to get proper field instead of null?
If you need more details please just ask.

You have to make two changes, one in the InstantiateIn implementation of your CustomItemTemplate so the container gets an ID as well. In this case I picked the value of _columnName:
public class CustomItemTemplate : ITemplate
{
// stuff omitted for brevity
// Override InstantiateIn() method
void ITemplate.InstantiateIn(Control container)
{
// set the ID of the container these fields are in!
container.ID = _columnName;
// rest of your code
// make sure hidden_time is still unique!
var hiddenInput = new HiddenField
{
ID = $"{_columnName.Replace(":", "_")}_hidden_time",
Value = _columnName
};
}
}
Then your button click implementation can leverage that ID when it sets off to find the control:
protected void bt_save_Click(object sender, EventArgs e)
{
// a GridViewRow has cells ...
foreach (GridViewRow row in gv_result_tw.Rows)
{
// ... the cells are of type DataControlFieldCell
foreach (DataControlFieldCell col in row.Cells)
{
// ... but we get some bonus fields as well
if (col.Controls.Count > 0)
{
// .. if we skip those
// ... we get a cell that has its ID set to the value
// that was used to generate the ID of the hiddenfield
var columnNameField = row.FindControl(col.ID + "_hidden_time") as HiddenField;
// columnNameField will not be null now ...
}
}
}
}

Related

How to get data from SQL database to store in to a combo box - C#

How can i get the value of outlet ID it on a comboBox?
here is my code to getting the values from Database and store it on a combobox.
public partial class Addstock : Form
{
String connectionString = ConfigurationManager.ConnectionStrings["TCConnectionString"].ConnectionString;
List<BOStockTransfer> StockList = new List<BOStockTransfer>();
int updateIndex = -1;
public Addstock()
{
InitializeComponent();
}
private void Addstock_Load(object sender, EventArgs e)
{
loadstock();
GetOutlets();
Getproduct();
GetGetWH();
cmdoutletID.Visible = false;
lbloutid.Visible = false;
cmdwh.Visible = false;
lblwh.Visible = false;
}
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletId";
}
}
Thank you for your help!
you are setting :
cmdoutletID.Visible = false;
what makes the combobox invisible
you have to set it as follows :
cmdoutletID.Visible = true;
After you added the images , the column name is outletID and Not outletId
so change your code as follows :
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletID";
cmdoutletID.ValueMember = "outletID";
cmdoutletID.Enabled = true;
}
}
The combo box has two properties which determine where it loads data from:
DisplayMember
ValueMember
The "ValueMember" property defines which named field populates the ListItem's "ValueProperty". That way, when you do combobox.SelectedItem.Value, you will get the value stored in the named field you specified for "ValueProperty".
Assuming that you are certain that your query is returning rows, perhaps try adding the items "manually" rather than relying on automatic databinding.
private void GetOutlets()
{
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
cmdoutletID.DisplayMember = "outletId";
cmdoutletID.ValueMember = "pkID";
cmdoutletID.BeginUpdate();
try
{
cmdoutletID.Items.Clear();
foreach (var row in ds_OutletList.Tables[0].Rows)
cmdoutletID.Items(new { outletid = row["outletid"], pkID = row["primaryKeyIDFieldName"] });
}
finally { cmdoutletID.EndUpdate(); }
}
Try this:
BOStockTransfer obj_StockTransfer = new BOStockTransfer();
DataSet ds_OutletList = obj_StockTransfer.GetOutlets(connectionString);
if (ds_OutletList.Tables[0].Rows.Count != 0)
{
cmdoutletID.DataSource = ds_OutletList.Tables[0];
cmdoutletID.DisplayMember = "outletname";
cmdoutletID.ValueMember = "outletId";
}
To capture selected value, for example on button click:
protected button1_Click(object o, EventArgs e)
{
var selectedId = cmboutletID.SelectedValue;
MessageBox.Show(selectedId);
}

'Find and Save' functionality not working

First time poster, long time lurker. I am having some trouble with my ASP.NET page, and I hope someone can help me resolve my issue.
Basically, I have a bunch of checkboxes in a gridview, and two buttons: a 'find' button, and a 'save' button. The 'find' can set the value of the checkbox, but if a user unchecks it, I want to capture that change when the user hits 'save'. Currently, it does not work.
Relevant ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="FindTransactions.aspx.cs" Inherits="Basic.FindTransactions" MasterPageFile="~/Trans.Master" %>
Relevant Code Behind here:
Page:
public partial class FindTransactions : System.Web.UI.Page
{
GridView _gridview = new GridView() { ID = "_gridView" };
DataTable _datatable = new DataTable();
Int32 _buyerID = new Int32();
protected void Page_Load(object sender, EventArgs e)
{
}
"Find" button:
protected void Find_Click(object sender, EventArgs e)
{
//truncated
_datatable.Rows.Add(
//filled with other data from a custom object.
);
ViewState["_datatable"] = _datatable;
ViewState["_buyerID"] = _buyerID;
BuildGridView((DataTable)ViewState["_datatable"],(Int32)ViewState["buyerID"]);
}
BuildGridView function:
protected void BuildGridView(DataTable d, Int32 b)
{
_gridview.DataKeyNames = new String[] {"Transaction ID"};
_gridview.AutoGenerateColumns = false;
_gridview.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
for(Int32 i = 0; i < d.Columns.Count; i++)
{
Boundfield boundfield = new BoundField();
boundfield.DataField = d.Columns[i].ColumnName.ToString();
boundfield.HeaderText = d.Columns[i].ColumnName.ToString();
_gridview.Columns.Add(boundfield);
}
_gridview.DataSource = d;
_gridview.DataBind();
//truncated
Panel1.Controls.Add(_gridview);
}
Row Bound Event handler:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String controlID = "checkBox";
CheckBox c = new CheckBox() { ID = controlID};
c.Enabled = true;
Boolean success;
Boolean v;
success = Boolean.TryParse(e.Row.Cells[8].Text, out v);
e.Row.Cells[8].Controls.Add(c);
if (success)
{
c.Checked = v;
if (c.Checked)
{
//Will uncomment once other things work
//e.Row.Visible = false;
}
}
else
{
c.Checked = false;
}
}
}
All of that works. Here is where it starts to break down:
"Save" button:
protected void Save_Click(object sender, EventArgs e)
{
//Both for troubleshooting and both return 0. (Expected for datatable)
Label1.Text = _gridview.Rows.Count.ToString();
Label2.Text = _datatable.Rows.Count.ToString();
/*truncated
*/
if (grid.Rows.Count == 0)
{
BuildGridView((DataTable)ViewState["infoTable"], (Int32)ViewState["guestID"]);
}
foreach (GridViewRow r in grid.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)r.FindControl("checkBox");
if (cb != null && cb.Checked)
{
//This never seems to modify the label.
//Will put code to modify database here.
Label2.Text += "Hi " + r.RowIndex.ToString();
}
}
}
}
After I hit the save button, PostBack occurs and GridView is empty (Rows.Count is 0). ViewState appears to be lost before I get a chance to loop through the GridView rows to determine the checkbox values.
At the end of it all, I just want to capture the status of those checkboxes, changed by user interaction or not, by hitting the 'Save' button.
I found some other articles, but a lot of them haven't worked when I tried implementing the various fixes.
This one seems to be the closest that describes my issue, and the code is structured similarly, but I don't quite understand how to implement the fix: GridView doesn't remember state between postbacks
[New simplified code to illustrate problem:]
namespace GridViewIssue
{
public partial class GridViewNoMaster : System.Web.UI.Page
{
GridView _gridView = new GridView() { ID = "_gridView" };
DataTable _dataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Find_Click(object sender, EventArgs e)
{
BuildDataTable();
List<String> list = new List<String>();
list.Add("1");
list.Add("User");
list.Add("10/12/2014");
foreach (String s in list)
{
_dataTable.Rows.Add(
list[0],
list[1],
list[2]
);
}
BuildGridView();
//Feedback.Text = _gridView.Rows.Count.ToString();
}
protected void Save_Click(object sender, EventArgs e)
{
Feedback.Text = "Save Clicked, PostBack: " + IsPostBack + ", GridView Row Count: " + _gridView.Rows.Count + ", GridView ViewState: " + _gridView.EnableViewState;
foreach (GridViewRow r in _gridView.Rows)
{
if(r.RowType == DataControlRowType.DataRow)
{
Feedback.Text = "In DataRow type" + _gridView.Rows.Count;
}
}
}
protected void BuildDataTable()
{
_dataTable.Columns.Add("Transaction ID", typeof(String));
_dataTable.Columns.Add("Name", typeof(String));
_dataTable.Columns.Add("Date", typeof(String));
}
protected void BuildGridView()
{
for (Int32 i = 0; i < _dataTable.Columns.Count; i++)
{
BoundField b = new BoundField();
b.DataField = _dataTable.Columns[i].ColumnName.ToString();
b.HeaderText = _dataTable.Columns[i].ColumnName.ToString();
_gridView.Columns.Add(b);
}
_gridView.DataKeyNames = new String[] { "Transaction ID" };
_gridView.AutoGenerateColumns = false;
_gridView.DataSource = _dataTable;
_gridView.DataBind();
Panel1.Controls.Add(_gridView);
}
}
}

How to filter the data bound to GridView control by the QueryString?

I am a new ASP.NET Web Forms developer and I am struggling now in with the best way of filtering the data by the value of QueryString before
binding it to the GridView control. I am binding the GridView to the GetData() method, and I would like to filter the data in the code-behind based
on the value of the QueryString if there is a QueryString. So should I do the checking of the QueryString in the BindGrid() method or in the
Page_Load() method? And how should I do it?
For your information, the GridView has a pagination capability as shown in the code-behind below.
Here's the C# code for the GetData():
public IEnumerable<Item> getData(Item itemObj)
{
List<Item> itemList = new List<Item>();
using (ATMSEntities context = new ATMSEntities())
{
itemList = (from item in context.Item
select new Item()
{
ItemId = item.ItemId,
Name = item.Name,
}).ToList();
if (itemObj.ItemId != 0)
{
itemList = itemList.Where(item => item.ItemId == itemObj.ItemId).ToList();
}
}
}
return itemList;
}
And here's the code-behind for the aspx page that has the GridView control:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["ItemId"] != null) //the filtration is not working here.
{
bindGrid();
}
}
private void bindGrid()
{
Item itemObj = new Item();
var result = itemObj.getData(itemObj).ToList();
gvItems.DataSource = itemObj.getData(itemObj);
gvItems.DataBind();
}
protected void gvItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvItems.PageIndex = e.NewPageIndex;
bindGrid();
}
Thanks in advance for your help.
You are not using the QueryString value to filter the list items. What you should be doing is this
private void bindGrid()
{
Item itemObj = new Item();
if(Request.QueryString["ItemId"] != null)
{
itemObj.ItemId = Convert.ToInt32(Request.QueryString["ItemId"]);
}
var result = itemObj.getData(itemObj).ToList();
gvItems.DataSource = itemObj.getData(itemObj);
gvItems.DataBind();
}

Gridview Edit/Update is not working?

Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.

Creating Gridview column Header by loading data from database

I want to bind my grid column header names by retrieving data from a table. This table has two fields, DomainID and DomainName, I want to display the DomainNames as Column header of the Grid.
Actually I am creating employee grid view. I want all the domain names of employee to be displayed as a header and i have to check the corresponding domain in Checkbox.
Please Give me some ideas.
Thanks in advance.
From what i understood....
Make a grid view
Create two columns:
a. TextBoxColumn
b. CheckBoxColumn
Set your column header using .HeaderText property
Add the columns to your data grid view
Query your database and get the data_table from it
using dgv.DataSource = data_table bind your data to the table
OR
Make a for loop for all rows in the data_table and add each row explicitly
For getting your checkboxes to work, handle the cellContentClick event of the data grid view and perform the necessary updates in your database.....
Hope it helps....
You could load the headers into a DataTable and then create them dynamically with a custom TemplateField.
Here's the aspx part:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" DataKeyNames="EmployeeID" runat="server" >
<SelectedRowStyle BackColor="Aqua" />
<Columns>
<asp:TemplateField HeaderText="Employee" SortExpression="Employee">
<ItemTemplate>
<asp:HiddenField ID="HiddenEmpID" Value='<%# Bind("EmployeeID") %>' runat="server" />
<asp:label runat="server" ID="LblEmployee" Text='<%# Bind("EmployeeName") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="BtnSave" Text="Save" runat="server" onclick="BtnSave_Click" />
Here's a complete sample:
public partial class GridTest : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
CreateGridColumns();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) BindGrid();
}
private void CreateGridColumns()
{
var tblDomain = GetDomains();
// Create dynamic TemplateFields
foreach (DataRow row in tblDomain.Rows)
{
String domainName = row.Field<String>("DomainName");
TemplateField field = new TemplateField();
//Initalize the DataField value.
field.ItemTemplate = new GridViewCheckBoxTemplate(ListItemType.Item, domaninName);
field.HeaderText = domainName;
//Add the newly created field to the GridView.
GridView1.Columns.Add(field);
}
}
private DataTable GetDomains()
{
var tblDomain = new DataTable();
tblDomain.Columns.Add("DomainID", typeof(int));
tblDomain.Columns.Add("DomainName");
tblDomain.Rows.Add(1, "Google.com");
tblDomain.Rows.Add(2, "Yahoo.com");
tblDomain.Rows.Add(3, "Msn.com");
tblDomain.Rows.Add(4, "Youtube.com");
tblDomain.Rows.Add(5, "Myspace.com");
tblDomain.Rows.Add(6, "Facebook.com");
tblDomain.Rows.Add(7, "Wikipedia.org");
return tblDomain;
}
private void BindGrid()
{
var tblDomain = GetDomains(); // load domains from database or wherever
var tblData = new DataTable();// load sample data
tblData.Columns.Add("EmployeeID", typeof(int));
tblData.Columns.Add("EmployeeName");
//add domains as DataTable-Columns
foreach (DataRow row in tblDomain.Rows)
{
String domaninName = row.Field<String>("DomainName");
//Add column from domain-name
tblData.Columns.Add(domaninName, typeof(bool)); //CheckBox-Checked is a boolean
}
//get some Employees and random checked state
var rnd = new Random();
var empRow = tblData.NewRow();
empRow["EmployeeID"] = 1;
empRow["EmployeeName"] = "Jon";
foreach (DataRow dom in tblDomain.Rows)
{
empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
}
tblData.Rows.Add(empRow);
empRow = tblData.NewRow();
empRow["EmployeeID"] = 2;
empRow["EmployeeName"] = "Eric";
foreach (DataRow dom in tblDomain.Rows)
{
empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
}
tblData.Rows.Add(empRow);
empRow = tblData.NewRow();
empRow["EmployeeID"] = 3;
empRow["EmployeeName"] = "Alain";
foreach (DataRow dom in tblDomain.Rows)
{
empRow[dom.Field<String>("DomainName")] = rnd.Next(0, 2) == 0;
}
tblData.Rows.Add(empRow);
GridView1.DataSource = tblData;
GridView1.DataBind();
}
// show how to retrieve all checkbox values and the according EmployeeID
protected void BtnSave_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 0) return;
var checkBoxColumns = GridView1.Columns.Cast<DataControlField>()
.Select((bf,index) => new{Field=bf, Index=index})
.Where(f => f.Field.GetType() == typeof(TemplateField) && ((TemplateField)f.Field).ItemTemplate.GetType() == typeof(GridViewCheckBoxTemplate))
.ToArray();
foreach (GridViewRow row in GridView1.Rows)
{
int EmployeeID = int.Parse(((HiddenField)row.FindControl("HiddenEmpID")).Value);
foreach (var f in checkBoxColumns)
{
String domain = f.Field.HeaderText;
bool isChecked = row.Controls[f.Index].Controls.OfType<CheckBox>().First().Checked;
}
}
}
}
Here's the custom ITemplate:
public class GridViewCheckBoxTemplate : ITemplate
{
ListItemType _templateType;
string _columnName;
public GridViewCheckBoxTemplate(ListItemType type, string colname)
{
_templateType = type;
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
break;
case ListItemType.Item:
var chb1 = new CheckBox();
chb1.DataBinding += new EventHandler(CB_DataBinding);
container.Controls.Add(chb1);
break;
case ListItemType.EditItem:
//As, I am not using any EditItem, I didnot added any code here.
break;
case ListItemType.Footer:
break;
}
}
void CB_DataBinding(object sender, EventArgs e)
{
CheckBox chb = (CheckBox)sender;
GridViewRow container = (GridViewRow)chb.NamingContainer;
object dataValue = ((DataRowView)container.DataItem)[_columnName];
chb.Checked = dataValue != DBNull.Value && (bool)dataValue;
}
}

Categories