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 ...
}
}
}
}
I'm just trying to create a single button "view" click for the data in the specific row for gridview and pass it to a Silverlight viewer.
Here's a "viewall" button I'm trying to figure out off of.
protected void btnViewAll_Click(object sender, EventArgs e)
{
string id = HttpContext.Current.Request.Headers["id"];
#if DEBUG
if (id == null)
id = "111"; // Use my own id for testing locally
#endif
using (aDataContext dc = new aDataContext())
{
var query = (from a in dc.aLists
where a.ID == id
select new
{
a.aNumber,
a.bNumber,
a.cNumber,
a.dNumber,
}
);
List<aListItem> List = new List<aListItem>();
foreach (var queryItem in query)
{
aList.Add(new aListItem()
{
aNumber = queryItem.aNumber,
bNumber = queryItem.bNumber,
cNumber = queryItem.cNumber,
dNumber = queryItem.dNumber
});
}
Session["aList"] = aList;
}
Session["Database"] = null;
Response.Redirect("Viewer.aspx" + "?UseList=true");
}
Solution 1:
It can be done with a ButtonField in the GridView:
Add the row-specific info to the DataKeyNames of the GridView (e.g. if the fields "name1" and "age2" of your data source are needed to view with your Silverlight viewer):
<asp:GridView ID="gvClients" DataKeyNames="name1,age2" ... >
Add a ButtonField to the GridView:
<asp:ButtonField ButtonType="Button" CommandName="View" Text="View" />
Set the RowCommand event handler (can be done in markup or in code):
gvClients.RowCommand += new GridViewCommandEventHandler(gvClients_RowCommand);
And process the command:
void gvClients_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
string name1 = (string)gvClients.DataKeys[rowIndex].Values["name1"];
int age2 = (int)gvClients.DataKeys[rowIndex].Values["age2"];
// Open docName with the viewer
...
}
Solution 2: An alternative, which avoids a postback, would be to use a a HyperLinkField:
<asp:HyperLinkField Text="View" DataNavigateUrlFormatString="Viewer.aspx?Name={0}&Age={1}" DataNavigateUrlFields="name1,age2" />
Using grid view binding it from code behind:
I want to bind a particular column data into a hyper link so when it clicked it should do a download.
How to do that ?
Below is my code :
for (int i = 0; i <= tbl.Columns.Count - 1; i++)
{
Telerik.Web.UI.GridBoundColumn boundfield = new Telerik.Web.UI.GridBoundColumn();
if (tbl.Columns[i].ColumnName.ToString() == "Row")
{
LinkButton lkbtn = new LinkButton();
lkbtn.CommandName = i;
lkbtn.CommandArgument = "dwnld";
lkbtn.Font.Underline = true;
lkbtn.Text = tbl.Columns(i).ColumnName.ToString();
boundfield.DataField = tbl.Columns(i).ColumnName.ToString()
boundfield.HeaderText = tbl.Columns(i).ColumnName.ToString();
GridView2.MasterTableView.Columns.Add(boundfield);
}
}
Why not use grid template column with link button.
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnDownload" OnClick="btnDownload_Click" runat="server">Download Something</asp:LinkButton>
</ItemTemplate>
</telerik:GridTemplateColumn>
protected void btnDownload_Click(object sender, EventArgs e)
{
LinkButton lbBtn = sender as LinkButton;
GridDataItem item = (GridDataItem)(sender as LinkButton).NamingContainer;
// Use item to get other details
...
...
}
I have tried to build one gridview with dynamic columns based the data source using the template fields in asp.net through code behind.
For that, to implement we have developed one class DynamicTemplate which implements the ITemplate interface. In that template fields i have inserted the LinkButton in each cell and when i click that cell link button i need to show the one Popup with selected cell value.
For Detailed Sample Please download from this link
For that I have created one Default.asxp page and wrote the following.
public partial class Default : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
LinkButton lnkButton;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}", i);
lnkButton.Visible = true;
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
if (ColumnValue == "EmpName")
{
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
}
else
{
dynTempItem.AddControl(lnkButton, "Text", ColumnValue);
lnkButton.Click += lnkButton_Click;
}
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
//////grdUserPivotDateTwo.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked')");
}
private DataTable getBindingData()
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpName"));
dt.Columns.Add(new DataColumn("Monday"));
dt.Columns.Add(new DataColumn("TuesDay"));
dt.Columns.Add(new DataColumn("WednesDay"));
dt.Columns.Add(new DataColumn("ThursDay"));
dt.Rows.Add("EmpOne", "p", "p", "p", "a");
dt.Rows.Add("EmpTwo", "p", "a", "p", "p");
dt.Rows.Add("EmpThree", "p", "p", "p", "a");
dt.Rows.Add("EmpFour", "p", "a", "p", "p");
dt.Rows.Add("EmpFive", "p", "p", "p", "a");
dt.Rows.Add("EmpSix", "a", "p", "p", "p");
return dt;
}
}
and corresponding DynamicTemplate class is
public class DynamicTemplate : System.Web.UI.ITemplate
{
System.Web.UI.WebControls.ListItemType templateType;
System.Collections.Hashtable htControls = new System.Collections.Hashtable();
System.Collections.Hashtable htBindPropertiesNames = new System.Collections.Hashtable();
System.Collections.Hashtable htBindExpression = new System.Collections.Hashtable();
public DynamicTemplate(System.Web.UI.WebControls.ListItemType type)
{
templateType = type;
}
public void AddControl(WebControl wbControl, String BindPropertyName, String BindExpression)
{
htControls.Add(htControls.Count, wbControl);
htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName);
htBindExpression.Add(htBindExpression.Count, BindExpression);
}
public void InstantiateIn(System.Web.UI.Control container)
{
PlaceHolder ph = new PlaceHolder();
for (int i = 0; i < htControls.Count; i++)
{
//clone control
Control cntrl = CloneControl((Control)htControls[i]);
switch (templateType)
{
case ListItemType.Header:
break;
case ListItemType.Item:
ph.Controls.Add(cntrl);
break;
case ListItemType.AlternatingItem:
ph.Controls.Add(cntrl);
ph.DataBinding += new EventHandler(Item_DataBinding);
break;
case ListItemType.Footer:
break;
}
}
ph.DataBinding += new EventHandler(Item_DataBinding);
container.Controls.Add(ph);
}
public void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
GridViewRow ri = (GridViewRow)ph.NamingContainer;
for (int i = 0; i < htControls.Count; i++)
{
if (htBindPropertiesNames[i].ToString().Length > 0)
{
Control tmpCtrl = (Control)htControls[i];
String item1Value = (String)DataBinder.Eval(ri.DataItem, htBindExpression[i].ToString());
Control ctrl = ph.FindControl(tmpCtrl.ID);
Type t = ctrl.GetType();
System.Reflection.PropertyInfo pi = t.GetProperty(htBindPropertiesNames[i].ToString());
pi.SetValue(ctrl, item1Value.ToString(), null);
}
}
}
private Control CloneControl(System.Web.UI.Control src_ctl)
{
Type t = src_ctl.GetType();
Object obj = Activator.CreateInstance(t);
Control dst_ctl = (Control)obj;
PropertyDescriptorCollection src_pdc = TypeDescriptor.GetProperties(src_ctl);
PropertyDescriptorCollection dst_pdc = TypeDescriptor.GetProperties(dst_ctl);
for (int i = 0; i < src_pdc.Count; i++)
{
if (src_pdc[i].Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
{
object collection_val = src_pdc[i].GetValue(src_ctl);
if ((collection_val is IList) == true)
{
foreach (object child in (IList)collection_val)
{
Control new_child = CloneControl(child as Control);
object dst_collection_val = dst_pdc[i].GetValue(dst_ctl);
((IList)dst_collection_val).Add(new_child);
}
}
}
else
{
dst_pdc[src_pdc[i].Name].SetValue(dst_ctl, src_pdc[i].GetValue(src_ctl));
}
}
return dst_ctl;
}
}
Here the Data showing in gridview is fine. Here the Issues are when i click on the linkButton the page reloads and no grid is displaying after the postback.
second issue is, for LinkButton the Click Event is not firing.
Please provide me the help full information/Sample to show the modal window when we click on the linkButton of the gridview.
You need to use ajax model popup expender.
Design a panel with your fields and use the model popup expender to display that popup
This link has the sample of it
www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/modalpopup/modalpopup.aspx
and in your link button click
you have to use show method to open popup
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
this code is generating a gridview only if it is not a postback, but when you click a linkbutton a postpack occurs and that's the reason why gridview doesnt show again when you click on the linkbutton.
add the following code(additional else part included to your if code) to show gridview when you click lnkButton
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
else
{
string ctrlName = Request.Params.Get("__EVENTTARGET").Trim();
if (!String.IsNullOrEmpty(ctrlName))
{
if (ctrlName.StartsWith("lnkButton"))
{
GenateGridView();
}
}
}
}
It will be a good choice to use CommandName property for the linkbutton on the Gridview and give it a specfic name and in the code file and exactly work with it in RowCommand event of your GridView as following in this example :
first here is the .aspx file :
<div>
<asp:GridView ID="GridViewStudents" runat="server" AutoGenerateColumns="False" OnRowCommand="GridViewStudents_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Stud_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelStudID" runat="server" Text='<%# Eval("Stud_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FKFather_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelFkFatherID" runat="server" Text='<%# Eval("Fk_Father_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name">
<ItemTemplate>
<asp:Label ID="LabelStudName" runat="server" Text='<%# Eval("Stud_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Class Name">
<ItemTemplate>
<asp:Label ID="LabelRowlevelName" runat="server" Text='<%# Eval("Stud_Level_Row_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDelete" runat="server" CommandArgument='<%# Eval("Stud_ID") %>' CommandName="Remove" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div style="direction: ltr">
<asp:Panel ID="Panel1" runat="server" Visible="false">
<asp:Label ID="Labelpopupmessage" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Buttonaccept" runat="server" Text="نعم" OnClick="Buttonaccept_Click" />
<asp:Button ID="Buttoncancel" runat="server" Text="لا" OnClick="Buttoncancel_Click" />
</asp:Panel>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:ModalPopupExtender runat="server" ID="ModalPopupExtenderStudent" PopupControlID="ButtonSubmit" TargetControlID="HiddenField1" CancelControlID="Buttoncancel">
</asp:ModalPopupExtender>
</div>
and here is the code implementation of my illustration :
protected void GridViewStudents_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
// I stored the ID of the selected Student I want to delete in a viewstate.
ViewState.Add("DeletedStudDetailID",Convert.ToInt32(e.CommandArgument));
ModalpopupExtender.Show();
}
}
// Here in the accept delete button I used that code ..
protected void Buttonaccept_Click(object sender, EventArgs e)
{
try
{
if (ViewState["DeletedStudDetailID"] != null)
{
StudentDetail StudDet = Data.StudentDetails.Single(SD => SD.Fk_Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.StudentDetails.DeleteOnSubmit(StudDet);
Student Stud = Data.Students.Single(S => S.Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.Students.DeleteOnSubmit(Stud);
Data.SubmitChanges();
}
this.ResultMessage = "Delete Done Sucessfully !!";
}
catch
{
this.ErrorMessage = "Delete operation disordered !!";
}
finally
{
ModalPopExtender.Hide();
}
}
I hope it helps in your issue and I wish you a happy day :) !!
First, your GridView will be created when calling GenateGridView method, so you have to call this method everytime you do post back, then your Page_Load should be
protected void Page_Load(object sender, EventArgs e)
{
GenateGridView();
}
Second, I would present you the other way to add LinkButton to GridView dynamically.
I modified your GenateGridView to just add only label into DynamicTemplate, also add this line gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound); to handle adding LinkButton.
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound);
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
I implement like this in RowDataBound event handler of the GridView to add LinkButton and hide the Label which we added it before:
protected void gvDynamicArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int j = 1; j < e.Row.Cells.Count; j++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}{1}", e.Row.DataItemIndex, j);
lnkButton.Click += new EventHandler(lnkButton_Click);
Label tempLabel = e.Row.FindControl("Label" + j) as Label;
lnkButton.Text = tempLabel.Text;
lnkButton.CommandArgument = tempLabel.Text;
tempLabel.Visible = false;
e.Row.Cells[j].Controls.Add(lnkButton);
}
}
}
You can also set any value to CommandArgument of LinkButton, then you can show it in the alert.
Final, seems you want to show some value in the alert, you may code like this
public void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
LinkButton lnk = (LinkButton)sender;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked, value " + lnk.CommandArgument + "')", true);
}
I'm totally having trouble with a Gridview that's been stumping me all day. I don't use Gridviews very often so some of this is confusing me and Google hasn't been as much help as I was hoping.
I'm trying to bind an object created through LINQ to a gridview and then do some updating.
XAML:
<asp:GridView runat="server" ID="GV1"
onrowediting="gridViewUsers_RowEditing"
onrowcancelingedit="gridViewUsers_RowCancelingEdit"
onrowdeleting="gridViewUsers_RowDeleting"
onrowupdating="gridViewUsers_RowUpdating"
>
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Code:
private void BindGrid()
{
List<Room> stuff = new List<Room>();
Hotel = dc1.Rooms.ToList();
GV1.DataSource = Hotel;
GV1.DataBind();
}
protected void gridViewUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
GV1.EditIndex = e.NewEditIndex;
BindGrid();
}
I want to just grab the Room object from the selected row and update it back to the database through LINQ. But I can't seem to get my hands on that object. My next attempt was to grab each entry from the row. So I found code like the example below. But everything is null.
protected void gridViewUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string tenant = ((TextBox)(GV1.Rows[e.RowIndex].FindControl("Tenant"))).Text;
string age = ((TextBox)(GV1.Rows[e.RowIndex].FindControl("Age"))).Text;
string roomno = ((TextBox)(GV1.Rows[e.RowIndex].FindControl("Room_No"))).Text;
BindGrid();
}
Try to set AutoGenerateColumns = false and provide columns manually.
Something like:
<asp:GridView runat="server" ID="GV1"
onrowediting="gridViewUsers_RowEditing"
onrowcancelingedit="gridViewUsers_RowCancelingEdit"
onrowdeleting="gridViewUsers_RowDeleting"
onrowupdating="gridViewUsers_RowUpdating"
AutoGenerateColumns = "false"
>
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField HeaderText="Tenant" DataField="Tenant" />
<asp:BoundField HeaderText="Age" DataField="Age" />
<asp:BoundField HeaderText="Room_No" DataField="Room_No" />
</Columns>
</asp:GridView>
EDIT:
Please add this code to your solution
public static int GetCellIndexByFieldHandle(this GridView grid, string fieldHandle)
{
int iCellIndex = -1;
for (int iColIndex = 0; iColIndex < grid.Columns.Count; iColIndex++)
{
if (grid.Columns[iColIndex] is DataControlField)
{
DataControlField col = (DataControlField)grid.Columns[iColIndex];
if ((col is BoundField && string.Compare(((BoundField)col).DataField, fieldHandle, true) == 0)
|| string.Compare(col.SortExpression, fieldHandle, true) == 0
|| col.HeaderText.Contains(fieldHandle))
{
iCellIndex = iColIndex;
break;
}
}
}
return iCellIndex;
}
/// <summary>
/// Gets the ordinal index of a TableCell in a rendered GridViewRow, using a text fieldHandle (e.g. the corresponding column's DataFieldName/SortExpression/HeaderText)
/// </summary>
public static int GetCellIndexByFieldHandle(this GridViewRow row, string fieldHandle)
{
return GetCellIndexByFieldHandle((GridView)row.Parent.Parent, fieldHandle);
}
And try
string tenant = ((TextBox)GV1.Rows[e.RowIndex].Cells[GV1.Rows[e.RowIndex].GetCellIndexByFieldHandle("Tenant")].Controls[0]).Text;
Try this code to access your textbox values .
protected void gridViewUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridViewUsers.Rows[e.RowIndex];
Textbox txtbxtenant = (TextBox)row.FindControl("Tenant");
string tenanat = Convert.toString(tentant.text);
Textbox txtbxAge =(Textbox)row.FindControl("Age");
string age = Convert.toString(Age.text);
// string roomno = ((TextBox)
//(GV1.Rows[e.RowIndex].FindControl("Room_No"))).Text;
// BindGrid();
}