How to create dynamic CheckBoxes inside a GridView? - c#

I have a GridView that displays the Approvers list. As shown in below image. I need to show CheckBoxes, if there are multiple Approvers in a column. Is it possible? If yes then how can I achieve it?
E.g The Approvers section has multiple Approver Names in the first row, for which I should show CheckBoxes.
The data displayed in the grid is available in a DataTable and the multiple Approvers are part of a single row hence I can't use TemplateField and display CheckBoxes.

Below is the solution. I could achieve this in method OnRowDataBound(). Not sure if this is the best way.
protected void grdApproverDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ApproverName = ((Label)e.Row.Cells[2].FindControl("lblANgrd")).Text;
string[] approvers = ApproverName.Split(';');
if (approvers.Count() > 1)
{
((Label)e.Row.Cells[2].FindControl("lblANgrd")).Text = "";
int i = 0;
foreach (var item in approvers)
{
CheckBox ckb = new CheckBox();
ckb.Text = item;
ckb.ID = i.ToString();
ckb.ID = "approvernamesdynamic_"+i.ToString();
ckb.Checked = true;
e.Row.Cells[2].Controls.Add(ckb);
i++;
}
}
}
}

Related

How to add a href for a button/link in ASP.NET GridView

I have an ASP.NET web app that processes some data from other sites and displays the information in a gridview. I don't know how many rows that gridview is going to have, nor how many columns.
In this gridview I have a templatefield which I used to add a Checkbox.
The rest of the columns are added using a DataTable that I bind to this gridview. The problem now is that after 10 columns, I have an URL which I want to display as a button, or a link. After this link I have x nr of columns.
How do I add this URL which is resting between static columns and dynamic columns, in a GridView with dynamic rows ?
I tried writing a href=link.. in the DataTable but it displays it as text.
I found an article that suggested something with HtmlDecode, but for that to work I would need to use boundfields which set the htmlencode = false..or something like that.
Is there any way of doing this ? or should I just move the link in the itemtemplate that has the checkbox as well and try to set it there ?
You can use the MatchGrid_RowDataBound method to look over the columns and add the buttons as you need.
Here is an example of how to add a button on RowDataBound:
How do I programmatically add a button to a gridview and assign it to a specific code-behind function?
You can use the OnRowDataBound for that. It will insert extra cells into the GridView. You could also insert extra column into the DataTable before binding it to the GridView.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//header
if (e.Row.RowType == DataControlRowType.Header)
{
//add 6 cells
for (int i = 1; i <= 6; i++)
{
TableHeaderCell headerCell = new TableHeaderCell();
if (i == 6)
{
headerCell.Text = "URL";
}
else
{
headerCell.Text = "Static " + i;
}
//add the new cell to the gridview
e.Row.Cells.AddAt(i, headerCell);
}
}
//normal row
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the current row to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//add 6 cells
for (int i = 1; i <= 6; i++)
{
TableCell cell = new TableCell();
if (i == 6)
{
cell.Text = string.Format("<a target=\"_blank\" href=\"{0}\">{0}</a>", row["myURL"]);
}
else
{
cell.Text = "Enter stuff here...";
}
//add the new cell to the gridview
e.Row.Cells.AddAt(i, cell);
}
}
}

Error while Dynamically creating Checkbox Header template in GridView

I used #Tim Schmelter code (Creating Gridview column Header by loading data from database) for ItemTemplate Checkboxes its working fine but when use HeaderTemplate, I'm getting an error at ITemplate --> CB_DataBinding --> object dataValue = ((DataRowView)container.DataItem)[_columnName]; saying NullReference since DataItem is Null. MyCode:
private void CreateGridColumns()
{
var tblAllowanceGroup = GetAllowanceGroup();
foreach (DataRow row in tblAllowanceGroup.Rows)
{ ...
field.HeaderTemplate = new GridViewCheckBoxTemplate(ListItemType.Header, AllowanceGroupName);
gvEmpSalaryStructure.Columns.Add(field);
}
private void BindGrid()
{
var tblAllowanceGroup = GetAllowanceGroup();
DataSet dsgrid = new DataSet();
DataTable dtgrid = new DataTable();
var empRow = dtgrid.NewRow();
dtgrid.Columns.Add("EmpName");
foreach (DataRow row in tblAllowanceGroup.Rows)
{
String AllowanceGroupName = row.Field<String>("AllowanceName");
//Add column from domain-name
dtgrid.Columns.Add(AllowanceGroupName, typeof(bool));
//CheckBox-Checked is a boolean
//This gives me only Header Text of Gridview
}
I Want GridView dynamically generated Headers which should contain Checkboxes. And want changes should I Make ITemplate CB_DataBinding to work with ListItemType.Header.
And When we check the checkbox in the Header column all the checkboxes in that column should be checked.
Thanks in Advance.
You can use the OnRowDataBound event of the gridview to loop the header row and insert a CheckBox in each Cell.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
CheckBox checkBox = new CheckBox();
checkBox.CssClass = "headerCheckBox";
checkBox.ID = "headerCheckBox_" + i;
e.Row.Cells[i].Controls.Add(checkBox);
}
}
}
And now you can bind a jQuery listener to the CheckBox class to handle the checking/unchecking of the entire column.

Getting data from GridView after changing the DataSource

I am trying to add the column names of a gridview to a dropdown list.
The problem is when I change the datasource of the gridview, it returns empty.
I am not sure whether the event is working properly, as it does not work with/without it.
I wanted to use the DataBindComplete event, but I could not see it so I tried DataBound instead.
private void BindTable()
{
if (ddTableSearch.SelectedIndex == 0)
{
tblCustomerTableAdapter customerAdapter = new tblCustomerTableAdapter();
GridView2.DataSource = customerAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 1)
{
tblInvoiceTableAdapter invoiceAdapter = new tblInvoiceTableAdapter();
GridView2.DataSource = invoiceAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 2)
{
tblEstimateTableAdapter estimateAdapter = new tblEstimateTableAdapter();
GridView2.DataSource = estimateAdapter.GetData();
GridView2.DataBind();
}
}
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
ddColumnSearch.Items.Clear();
for (int i = 0; i < GridView2.Columns.Count; i++)
{
ddColumnSearch.Items.Add(new ListItem(GridView2.Columns[i].ToString()));
}
}
What am I doing wrong?
The databound event runs for each record in the gridview. So one issue is that each time you are clearing out the items you added before. Another issue is that you need to get the data from the EventArgs instead of from the gridview.columns since those are not there until after all the data is bound. I think all you need to do is get the data from the header row:
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
if(e.Row.RowType != DataControlRowType.Header) return; //only continue if this is hdr row
ddColumnSearch.Items.Clear();
foreach (TableCell cell in e.Row.Cells)
{
ddColumnSearch.Items.Add(new ListItem(cell.Text));
}
}

populating DropDownList in a gridview with array elements

I have been trying to Populate a DropDownList in my gridview with array elements . The array consists of the column names from another gridview .The array element seems to get the column names from its source but i can not figure out how to give that to the dropdownlist.Here is my code-:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] excel = new string[250];
DataTable dtt = (DataTable)Session["griddata"]; //griddata is the gridview data from another page
for (int i = 0; i < dtt.Columns.Count; i++)
{
excel[i] = dtt.Columns[i].ColumnName;
}
Session["exceldata"] = excel;
ArrayList mylist= (ArrayList)Session["exceldata"];
DropDownList drd = (DropDownList)GridView2.FindControl("DrdDatabase");
drd.DataSource = mylist;
drd.DataTextField = "GridView";
drd.DataBind();
}
Thanks in Advance :)
Here is the logic which you can use to populate your dropdownlist.
->
Loop at the array.
{
For each item in array
{
add item to dropdownlist.items
}
}
Sorry for not providing the exact code as I dont have .net editor at my disposal right now but you can use the logic to implement it.
regards.
You could simply loop it and add the ListItems programmatically:
DropDownList drd = (DropDownList)GridView1.FindControl("DrdDatabase");
foreach(string colName in mylist)
drd.Items.Add(new ListItem( colName ));
However, are you sure that you find your DropDownList via GridView1.FindControl? I assume you get a NullRefernceException there. Then you need to show us where it actually is.
If it is in a TemplateField of the GridView you should use the RowDataBound event:
private ArrayList ExcelData
{
get {
object excel = Session["exceldata"];
if (excel == null) Session["exceldata"] = new ArrayList();
return (ArrayList)Session["exceldata"];
}
set {
Session["exceldata"] = value;
}
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
foreach (string colName in ExcelData)
ddl.Items.Add(new ListItem(colName));
}
}

getting the rowindex of gridview based on the label control value

I have a label control on my page and beneath the label control there is a Gridview.The value that exists in the label control also exists in the Gridview. The label control has value like this
3244|Yellow Ink| Test Link
In the gridview, I have a value 3244 too
3244 yello Ink Test Link
3255 Green Link Test2
I want the row Index of 3244 in my code behind as soon as the page loads. Is their any way to do it.
Not knowing what type of data source you have, one way of doing it would be with LINQ like this:
protected void Page_Load(object sender, EventArgs e)
{
// Fetch the text from your label. (I'm assuming that you have only one label with the text "3244|Yellow Ink| Test Link".
string text = Label1.Text;
// Find the first row or return null if not found.
var resultRow = GridView1.Rows.Cast<GridViewRow>().FirstOrDefault(row =>
{
// Get the id (that I'm guessing is the first (0-index) column/cell)
var id = row.Cells[0].Text;
// Return true/false if the label text starts with the same id.
return text.StartsWith(id);
});
if (resultRow != null)
{
var index = resultRow.RowIndex;
}
}
A shorter version would look like this:
var resultRow = GridView1.Rows.Cast<GridViewRow>()
.FirstOrDefault(r => text.StartsWith(r.Cells[0].Text));
protected void btnJobAppSelected_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridViewJobApplications.Rows)
{
int rowIndex = ((sender as LinkButton).NamingContainer as GridViewRow).RowIndex;
LinkButton btnJobAppSelected = (LinkButton)GridViewJobApplications.Rows[rowIndex].FindControl("btnJobAppSelected");
}
}
In your page load after populating gridView, you can do that like this:
String searchValue = "3244 ";
int rowIndex = -1;
foreach (GridViewRow row in GridViewID.Rows)
{
if (row.Cells[0].Text.ToString().Equals(searchValue))
{
rowIndex = row.RowIndex;
break;
}
}
int YourIndex = rowIndex;

Categories

Resources