gridview row with javascript - c#

I'm having trouble selecting a row in a gridview, I have javascript code
function SelectRow(row) {
var _selectColor = "#303030";
var _normalColor = "#909090";
var _selectFontSize = "3em";
var _normalFontSize = "2em";
// get all data rows - siblings to current
var _rows = row.parentNode.childNodes;
// deselect all data rows
try {
for (i = 0; i < _rows.length; i++) {
var _firstCell = _rows[i].getElementsByTagName("td")[0];
_firstCell.style.color = _normalColor;
_firstCell.style.fontSize = _normalFontSize;
_firstCell.style.fontWeight = "normal";
}
}
catch (e) { }
// select current row (formatting applied to first cell)
var _selectedRowFirstCell = row.getElementsByTagName("td")[0];
_selectedRowFirstCell.style.color = _selectColor;
_selectedRowFirstCell.style.fontSize = _selectFontSize;
_selectedRowFirstCell.style.fontWeight = "bold";
}
and on the databound event of the grid I have
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow Row in GridView1.Rows){
if (e.Row.RowType == DataControlRowType.DataRow)
{
// javascript function to call on row-click event
e.row.Attributes.Add("onClick", "javascript:void SelectRow(this);");
}
}
}
but this line is giving error
if (e.Row.RowType == DataControlRowType.DataRow) error message: 'System.EventArgs' does not contain a definition for 'row' and no
extension method 'row' accepting a first argument of type
'System.EventArgs' could be found (are you missing a using directive
or an assembly reference?)
Thanks

You are using incorrect event. You use DataBound, but need to use RowDataBound
RowDataBound has GridViewRowEventArgs args, and they have needed way to do it

Related

How to cast LiteralControl to LinkButton in C#

protected void gvDispMsg_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView hGrid = (GridView)sender;
GridViewRow gvrRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableHeaderCell tcCellSub1 = new TableHeaderCell();
tcCellSub1.Controls.Add(lblDDLBlank);
gvrRow.Cells.Add(tcCellSub1);
gvDispMsg.Controls[0].Controls.AddAt(0, gvrRow);
LinkButton btnSort;
System.Web.UI.WebControls.Image image;
//iterate through all the header cells
foreach (TableCell cell in e.Row.Cells)
{
//check if the header cell has any child controls
if (cell.HasControls())
{
//get reference to the button column
btnSort = (LinkButton)cell.Controls[0];
image = new System.Web.UI.WebControls.Image();
if (ViewState["sortExp"] != null)
{
//Do something
}
}
}
}
}
I am getting the following error in line btnSort = (LinkButton)cell.Controls[0];:
Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.LinkButton'.
How can I resolve the error.
I know this is an old question, but in case someone finds it in a search in the future this is the correct way to cast a link button from a grid view:
var btnSort = (LinkButton)GridView1.Rows[i].Cells[k].Controls[1];

Accessing dynamically generated dropdownlist in Gridview_RowUpdating event

I am using Gridview with AutoGenerateColumns="True", so gridview columns are generated dynamically. Now in case of edit, I am adding dropdownlist dynamically for one of the field in the gridview. Please see following code:
protected void grdViewConfig_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewConfig.EditIndex = e.NewEditIndex;
BindGridView();
clientBAL = new TMIWsBALClient();
var lstAppIds = clientBAL.GetDistinctApplicationIds();
GridViewRow grdRow = grdViewConfig.Rows[e.NewEditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell )grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
DropDownList drpDwnAppIds = new DropDownList();
drpDwnAppIds.ID = "drpDwnAppIds";
drpDwnAppIds.DataSource = lstAppIds;
drpDwnAppIds.DataBind();
var tb = dcField.GetAllControlsOfType<TextBox>(); ;// grdRow.Cells[i].GetAllControlsOfType<TextBox>();
TextBox firstTb = (TextBox)tb.First();
foreach (ListItem lstItem in drpDwnAppIds.Items)
{
if (firstTb.Text.Equals(lstItem.Text, StringComparison.CurrentCultureIgnoreCase))
{
lstItem.Selected = true;
}
}
dcField.Controls.Remove(firstTb);
dcField.Controls.Add(drpDwnAppIds);
}
}
}
}
Now in Gridview_RowUpdating event, I am trying to fetch the dropdownlist in similar way, but I am unable to get it. GetAllControlsOfType() is an extension method, which will return all the child controls under selected parent. In this case, parent is gridview cell and child control is dropdownlist. But it is returning null.
protected void grdViewConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
strTableName = txtTable.Text.Trim();
string strAppId;
GridViewRow grdRow = grdViewConfig.Rows[grdViewConfig.EditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell)grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
var drpDwn = dcField.GetAllControlsOfType<DropDownList>();
DropDownList drpDwnAppIds = (DropDownList)drpDwn.First();
strAppId = drpDwnAppIds.SelectedValue;
}
}
}
}
What am I missing? Please help. Also let me know if more information is needed.
Thank you in advance.
Dynamically generated controls need to be recreated on every postback. In your case the DropDownList controls you created no longer exist when you hit the grdViewConfig_RowUpdating handler.
Generally in this sort of case you would set AutoGenerateColumns to false and manually define your columns which would allow you to define a TemplateField which contains an ItemTemplate for read only mode and an EditItemTemplate for edit mode which could then contain your DropDownList.

gridview button

I apologize if this is a real simple question, but I can't find anyone else to ask. I have a gridview with a button column. I'm trying to use the button column to send a filename to another page. I pulled this code off of another solution here, but I get an error: "Does not contain a definition for 'Item'" on this line: ListViewDataItem item = (ListViewDataItem)e.Item; and I have no idea which Using-namespace (is that what they are called?) to use.
protected void gvFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "edit")
{
ListViewDataItem item = (ListViewDataItem)e.Item;
int index = item.DataItemIndex;
string fileID = ((ListView)sender).DataKeys[index]["fileID"].ToString();
Response.Redirect("irMain.aspx?#filename=" + fileID);
}
}
I suppose you are dealing with a gridView not a ListView, then the code should be
protected void gvFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "edit")
{
int index = Convert.ToInt32(e.CommandArgument);
string fileID = ((GridView)sender).DataKeys[index]["fileID"].ToString();
Response.Redirect("irMain.aspx?#filename=" + fileID);
}
}

Adding data dynamically to a asp literal control inside a grid view

I'm trying to add data to a literal which place inside a gridview. Currently code look like this
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = "<h3>" + list.title + "</h3>";
info.Text += "<h4>" + list.description + "</h4>";
}
}
}
This will generate an error
Object reference not set to an instance of an object.
If anyone has an idea about this it will be great help
Thanks
Ensure you're only operating on the data rows, and not the header, footer, separator, pager, etc. The enum for this is DataControlRowtype. This is why your info object/reference is null, as it operates on the header first.
Check that the e.Row.RowType is of type DataRow.
For safety, also check that your info is not null.
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null && info !=null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = string.Format("<h3>{0}</h3><h4>{1}</h4>",
list.title, list.description);
}
}
}
}

Binding dropdown list in a gridview edit item template

i can bind the dropdownlist in the edit item template. The drop down list is having null values.
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList drpBuildServers = new DropDownList();
if (grdDevelopment.EditIndex == e.Row.RowIndex)
{
drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
}
}
also getting an error
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
I had problems with find control, in the end I used a little bit of recursion to find the control:
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Then to find your control make this call:
drpBuildServers = (DropDownList) FindControlRecursive(e.Row.Cells[0], "ddlBuildServers");
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpBuildServers;
drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;
if (drpBuildServers != null)
// Write your code here
}
}
try http://www.codeproject.com/KB/webforms/editable_gridview_control.aspx , it could be helpful
Its a solution for me:
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpBuildServers;
drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;
if (drpBuildServers != null)
// Write your code here
}
}

Categories