How can I change the field type on a GridView at runtime with AutoGenerate="True"? - asp.net

I've created a control that extends the BoundField control to do some special processing on the data that's passed into it.
I now have a grid that has AutoGenerateColumns="true", by which I'd like to intercept the HeaderText, see if it's a particular value and then swap in the "SpecialBoundField" instead. I've tried using the OnDataBinding event to loop through the columns, but at this point there are no columns in the grid. I think that RowDataBound and DataBound are too late in the game so not sure what to do.
My next thought was to override the grid control itself to add in a "AutoGeneratingColumn" event in
protected virtual AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)
Can anyone help or point me in a better direction? Thanks!

If you have both fields coming back in the dataset, I would suggest setting the column visibilities instead of trying to dynamically add or change the datafields. Invisible columns don't render any HTML, so it would just be a matter of looking at the header row when it gets bound, checking the field you're interested in, and setting the column visibility.
void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (e.Row.Cells[1].Text = "BadText")
{
myGridView.Columns[1].Visible = false;
myGridView.Columns[5].Visible = true;
}
}
}

What I ended up with:
public class SpecialGridView : GridView
{
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
ModifyData(e);
base.OnRowDataBound(e);
}
IList<string> _columnNames = new List<string>();
protected void ModifyData(GridViewRowEventArgs e)
{
LoadColumnNames(e);
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
string currentColumnName = _columnNames[i];
if (IsSpecialColumn(currentColumnName))
{
string text = e.Row.Cells[0].Text;
bool isSpecialData = text.ToUpper() == "Y";
if (isSpecialData)
{
e.Row.Cells[i].CssClass += " specialData";
}
}
}
}
}
private void LoadColumnNames(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
_columnNames.Add(cell.Text);
}
}
}
private bool IsSpecialColumn(string currentColumnName)
{
foreach (string columnName in SpecialColumnNames)
{
if (currentColumnName.ToUpper() == columnName.ToUpper())
{
return true;
}
}
return false;
}
private IList<string> _specialColumnNames = new List<string>();
public IList<string> SpecialColumnNames
{
get { return _specialColumnNames; }
set { _specialColumnNames = value; }
}
}

Related

Hiding GridView Columns on RunTime

i am trying to hid some columns of gridView on run time by matching their HeaderText but its not working for me. here is the code i am trying
protected void gridview_rowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (DataControlField col in gvRecoed.Columns)
{
try
{
if (col.HeaderText == cat_check.SelectedItem.Text.Trim())
{
col.Visible = false;
}
}
catch (Exception exe)
{ }
}
}
cat_check is a CheckBoxList
Why do you want to hide the column in RowDataBound which is triggered for every row in the grid?
Instead you could use the DataBound event which is called once after the grid was databound.
protected void gridview_DataBound(object sender, EventArgs e)
{
if(cat_check.SelectedItem != null)
{
string columnName = SelectedItem.Text;
var column = gridView1.Columns.Cast<DataControlField>()
.FirstOrDefault(c => c.HeaderText == columnName);
if (column != null) column.Visible = false;
}
}
protected void gridview_rowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlField col in gvSource.Columns)
{
try
{
if (col.HeaderText == cat_check.SelectedItem.Text.Trim())
{
col.Visible = false;
}
}
catch (Exception exe)
{ }
}
}
}
Here is the simple answer.
Create css as below
.classHide{
display:none
}
then instead of col.hide,just assign classHide cssclass to the column.
e.g. col.cssclass="classHide"

How to get the cell value by column name not by index in GridView in asp.net

I am having a gridview in asp.net and now I want the cell value by the column name but not by the cell index.
How would be it possible by retrieving the cell value by the cell column name
GridView does not act as column names, as that's it's datasource property to know those things.
If you still need to know the index given a column name, then you can create a helper method to do this as the gridview Header normally contains this information.
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
remember that the code above will use a BoundField... then use it like:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "myDataField");
string columnValue = e.Row.Cells[index].Text;
}
}
I would strongly suggest that you use the TemplateField to have your own controls, then it's easier to grab those controls like:
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and then use
string columnValue = ((Label)e.Row.FindControl("lblName")).Text;
Although its a long time but this relatively small piece of code seems easy to read and get:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index;
string cellContent;
foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
{
if( tc.Text.Equals("yourColumnName") )
{
index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
break;
}
}
}
You can use the DataRowView to get the column index.
void OnRequestsGridRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var data = e.Row.DataItem as DataRowView;
// replace request name with a link
if (data.DataView.Table.Columns["Request Name"] != null)
{
// get the request name
string title = data["Request Name"].ToString();
// get the column index
int idx = data.Row.Table.Columns["Request Name"].Ordinal;
// ...
e.Row.Cells[idx].Controls.Clear();
e.Row.Cells[idx].Controls.Add(link);
}
}
}
For Lambda lovers
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var boundFields = e.Row.Cells.Cast<DataControlFieldCell>()
.Select(cell => cell.ContainingField).Cast<BoundField>().ToList();
int idx = boundFields.IndexOf(
boundFields.FirstOrDefault(f => f.DataField == "ColName"));
e.Row.Cells[idx].Text = modification;
}
}
Based on something found on Code Project
Once the data table is declared based on the grid's data source, lookup the column index by column name from the columns collection. At this point, use the index as needed to obtain information from or to format the cell.
protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)((GridView)sender).DataSource;
int colIndex = dt.Columns["MyColumnName"].Ordinal;
e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
}
}
Header Row cells sometimes will not work. This will just return the column Index. It will help in a lot of different ways. I know this is not the answer he is requesting. But this will help for a lot people.
public static int GetColumnIndexByHeaderText(GridView gridView, string columnName)
{
for (int i = 0; i < gridView.Columns.Count ; i++)
{
if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
{
return i;
}
}
return -1;
}
A little bug with indexcolumn in alexander's answer:
We need to take care of "not found" column:
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
int foundIndex=-1;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
{
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
{
foundIndex=columnIndex;
break;
}
}
columnIndex++; // keep adding 1 while we don't have the correct name
}
return foundIndex;
}
and
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "myDataField");
if( index>0)
{
string columnValue = e.Row.Cells[index].Text;
}
}
}
We can get it done in one line of code. No need to loop through anything or call other methods.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string cellValue = e.Row.Cells[e.Row.Cells.GetCellIndex(e.Row.Cells.Cast<DataControlFieldCell>().FirstOrDefault(cell => cell.ContainingField.HeaderText == "columnName"))].Text;
}
}
//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
{//start getGridviewValue
//scan gridview for cell value
string result = Convert.ToString(functionsOther.getCurrentTime());
for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
{//start i for
if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
{//start check field match
result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
break;
}//end check field match
}//end i for
//return
return result;
}//end getGridviewValue
It is possible to use the data field name, if not the title so easily, which solved the problem for me. For ASP.NET & VB:
e.g. For a string:
Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()
e.g. For an integer:
Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())
protected void CheckedRecords(object sender, EventArgs e)
{
string email = string.Empty;
foreach (GridViewRow gridrows in GridView1.Rows)
{
CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");
if (chkbox != null & chkbox.Checked)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in gridrows.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals("UserEmail"))
break;
columnIndex++;
}
email += gridrows.Cells[columnIndex].Text + ',';
}
}
Label1.Text = "email:" + email;
}
protected void gvResults_PreRender(object sender, EventArgs e)
{
var gridView = (GridView)sender;
gridView.GetColumnByName("YourDataBoundDataField").Visible = true;
}
Extension:
public static DataControlField GetColumnByName(this GridView gridView, string columnName)
{
int columnIndex = -1;
for (int i = 0; i < gridView.Columns.Count; i++)
{
if (gridView.Columns[i].HeaderText.Trim().Equals(columnName, StringComparison.OrdinalIgnoreCase))
{
columnIndex = i;
break;
}
}
if (columnIndex == -1)
{
throw new ArgumentOutOfRangeException("GridViewRow does not have the column with name: " + columnName);
}
return gridView.Columns[columnIndex];
}
The primary reason this would be difficult is because gridview cells do not have accessible cell names (ugh).
In order to work around this handicap you can make an extension method (mine is in VB.NET, but #Дмитрийh seems to have a similar solution in C#).
To work around this ensure the HeaderText of the gridview cells have the same value as the cellnames and grab the values via that HeaderText name.
Here is extension methods you would need for strings and integers in a VB.NET code snippet that I made
Public Shared Function GetStringByCellName(pGridViewRow As GridViewRow, pCellName As String) As String
For Each myCell As DataControlFieldCell In pGridViewRow.Cells
If myCell.ContainingField.ToString() = pCellName Then
Return myCell.Text
End If
Next
Return Nothing
End Function
And the difference for integers being a parse/cast
Public Shared Function GetIntegerByCellName(pGridViewRow As GridViewRow, pCellName As String) As Integer
For Each myCell As DataControlFieldCell In pGridViewRow.Cells
If myCell.ContainingField.ToString() = pCellName Then
Return Integer.Parse(myCell.Text)
End If
Next
Return Nothing
End Function
And calling the functions would look like this if it were in a class.
Dim columnNamesStringValue As String = ExtensionMethodsClassName.GetStringByCellName(pGridViewRow, "stringOfColumnName")
Dim columnNamesIntegerValue As Integer = ExtensionMethodsClassName.GetIntegerByCellName(pGridViewRow, "stringOfColumnName")
have in mind that you may not always get a value, and instead may get Nothing
Before you (perhaps try to put the value in your database), ensure it is not nothing first by checking that it is not nothing. If you wanted to insert into the database, however, it may be better to return a System.DBNull instead of Nothing from the extension methods I provided.
(DO NOT CHECK AND INSERT THE OTHER NULLS or Nothing AS DBNull'S. DIFFERENT TYPES OF NULL'S AND NOTHINGS ARE NOT EQUAL)
If (columnNamesStringValue IsNot Nothing)

Textbox value null when trying to access it

namespace Dynamic_Controls.Dropdowndynamic
{
public partial class DropdowndynamicUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (ControlCount != 0)
{
Recreatecontrols();
}
}
private void Recreatecontrols()
{
// createtextboxes(ControlCount);
createtextboxes(2);
}
protected void createtextboxes(int ControlCount)
{
DynPanel.Visible = true;
for (int i = 0; i <= ControlCount; i++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + this.DynPanel.Controls.Count;
tb.Text = "EnterTitle" + this.DynPanel.Controls.Count;
tb.Load+=new EventHandler(tb_Load);
tb.Visible = true;
tb.EnableViewState = true;
DynPanel.Controls.Add(tb);
DynPanel.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 newControlCount = Int32.Parse(DropDownList1.SelectedValue);
//createtextboxes(newControlCount);
//ControlCount+=newControlCount;
createtextboxes(2);
}
protected void Button1_Click(object sender, EventArgs e)
{
readtextboxes();
}
public void readtextboxes()
{
string x = string.Empty;
for (int a = 0; a < DynPanel.Controls.Count; a++)
{
foreach (Control ctrl in DynPanel.Controls)
{
if (ctrl is TextBox)
{
x = ((TextBox)ctrl).Text;
}
x+=x+("\n");
}
Result.Text = x;
}
}
private Int32 ControlCount
{
get
{
if (ViewState["ControlCount"] == null)
{
ViewState["ControlCount"] = 0;
}
return (Int32)ViewState["ControlCount"];
}
set
{
// ViewState["ControlCount"] = value;
ViewState["ControlCount"] = 2;
}
}
private void tb_Load(object sender, EventArgs e)
{
LblInfo.Text = ((TextBox)sender).ID + "entered";
}
}
}
Are you adding these controls dynamically in Page_Load (by, I'm assuming, calling your AddRequiredControl() method)? If so, is it wrapped in a conditional which checks for IsPostBack? The likely culprit is that you're destructively re-populating the page with controls before you get to the button click handler, so all the controls would be present but empty (as in an initial load of the page).
Also, just a note, if you're storing each control in _txt in your loop, why not refer to that variable instead of re-casting on each line. The code in your loop seems to be doing a lot of work for little return.
You need to recreate any dynamically created controls on or before Page_Load or they won't contain postback data.
I'm not entirely clear what happens on DropdownList changed - are you trying to preserve anything that has been entered already based on the textboxes previously generated?
In any event (no pun intended) you need to recreate exactly the same textboxes in or before Page_Load that were there present on the postback, or there won't be data.
A typical way to do this is save something in ViewState that your code can use to figure out what to recreate - e.g. the previous value of the DropDownList. Override LoadViewState and call the creation code there in order to capture the needed value, create the textboxes, then in the DropDownList change event, remove any controls that may have been created in LoadViewState (after of course dealing with their data) and recreate them based on the new value.
edit - i can't figure out how your code works now, you have AddRequiredControl with parameters but you call it with none. Let's assume you have a function AddRequiredControls that creates all textboxes for a given DropDownList1 value, and has this signature:
void AddRequiredControls(int index)
Let's also assume you have a PlaceHolder called ControlsPlaceholder that will contain the textboxes. Here's some pseudocode:
override void LoadViewState(..) {
base.LoadViewState(..);
if (ViewState["oldDropDownIndex"]!=null) {
AddRequiredControls((int)ViewState["oldDropDownIndex"]);
}
}
override OnLoad(EventArgs e)
{
// process data from textboxes
}
void DropDownList1_SelectedIndexChanged(..) {
ControlsPlaceholder.Controls.Clear();
AddRequiredControls(DropDownList1.SelectedIndex);
ViewState["oldDropDownIndex"]=DropDownList1.SelectedIndex;
}

How to use ColumnName in GridView control to hide some columns

I want to hide few columns of a gridview before they gets displayed.
I want to do it by create a common function which can be used by multiple controls.
I am using an extension and would like to know how it can be done.
Here is my code
protected void btnStandardView_Click(object sender, EventArgs e)
{
_viewTypeDl = new ViewTypeDL();
DataTable dt = _viewTypeDl.GetStandardView();
gvViewType.Source(_viewTypeDl.GetStandardView(),"ColorCode");
ViewState["request"] = "Standard View";
}
public static void Source(this CompositeDataBoundControl ctrl, DataTable dt, params string[] ColumnsToHide)
{
ctrl.DataSource = dt;
ctrl.DataBound += new GridViewRowEventHandler(ctrl_DataBound);
ctrl.DataBind();
}
static void ctrl_DataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells["ColorCode"].Visible = false;
}
I want to create an extension to hide or show columns provided in the list as an array.
1st function is used on page. While below two functions are needs to be used for multiple applications
There are two ways you can meet your requirement.
set gvViewType.Columns[i].visble = false;
Allow css to handle the hidden columns for you.
.hidden
{
display:none;
}
.visble
{
display:block;
}
//This is the Gridview event.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Cells Represent the Column
e.Row.Cells[0].CssClass = "hidden";
}
else if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].CssClass = "hidden";
}
}

Disable a checkbox created at runtime

In my asp.net application i have created checkboxes at runtime. I want to disable the checked checkbox when i click on a button. How do I achieve this? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 12; i++)
{
tr = new TableRow();
tr.BorderStyle = BorderStyle.Groove;
for (int j = 0; j < 18; j++)
{
tc = new TableCell();
tc.BorderStyle = BorderStyle.Groove;
ch = new CheckBox();
tc.Controls.Add(ch);
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IDictionaryEnumerator RoleCheckBoxEnumerator = mRoleCheckBoxList.GetEnumerator();
while (RoleCheckBoxEnumerator.MoveNext())
{
CheckBox RoleCheckBox = (CheckBox)RoleCheckBoxEnumerator.Value;
string BoxRoleName = (string)RoleCheckBox.Text;
if (RoleCheckBox.Checked == true)
{
RoleCheckBox.Enabled = false;
break;
}
}
}
One rule-of-thumb while dealing with dynamically generated user controls is that you have to add them to the container on EVERY POSTBACK.
Just modify your code to generate the controls on every postback, and your code will start working like a charm!
EDIT
I am unsure what the ch variable is. I have assumed that its a checkbox. If I am correct, then all you have to do is to modify these lines
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
to this
//if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
EDIT 2
This is the code for generating 10 checkboxes dynamically -
protected void Page_Init(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = new CheckBox();
c.ID = "chk" + i.ToString();
c.Text = "Checkbox " + (i + 1).ToString();
container.Controls.Add(c);
}
}
Check the checkboxes when the page renders on the client side, click the button. This will cause a postback and the checkboxes will be generated again. In the click event of the button, you'll be able to find the checkboxes like this -
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = container.FindControl("chk" + i.ToString()) as CheckBox;
//Perform your relevant checks here, and disable the checkbox.
}
}
I hope this is clear.
Maybe
RoleCheckBox.Parent.Controls.Remove(RoleCheckBox);
You are not getting a proper reference to your checkboxes - mRoleCheckBoxList is not mentioned as part of your checkbox creation.
Try the following in your button event handler:
foreach (TableRow row in Table1.Rows)
foreach (TableCell cell in row.Cells)
{
CheckBox check = (CheckBox)cell.Controls[0];
if (check.Checked) check.Enabled = false;
}
Always when creating dynamic controls in .Net create them here:
protected override void CreateChildControls()
{
base.CreateChildControls();
this.CreateDynamicControls();
} //eof method
and in the PostBack find the them either from the event trigger or from a non-dynamic control:
/// <summary>
/// Search for a control within the passed root control by the control id passed as string
/// </summary>
/// <param name="root">the upper control to start to search for</param>
/// <param name="id">the id of the control as string</param>
/// <returns></returns>
public virtual Control FindControlRecursively(Control root, string id)
{
try
{
if (root.ID == id)
{
return root;
} //eof if
foreach (Control c in root.Controls)
{
Control t = this.FindControlRecursively( c, id);
if (t != null)
{
return t;
} //eof if
} //eof foreach
} //eof try
catch (Exception e)
{
return null;
} //eof catch
return null;
} //eof method

Resources