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];
Related
I have a gridview and need to add controls to header row. I am able to add text, but how can I add a hyperlink to the header row.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Logistics Details";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);
GridView1.Controls[0].Controls.AddAt(0, HeaderGridRow);
HyperLink hl = new HyperLink();
hl.ID = "hlDetail";
hl.Text = "Details";
//the below line doesn't add controls
HeaderGridRow.Controls.Add(hl);
}
}
I think you would have to add the control to a specific Cell within the row, e.g.
HeaderGridRow.Cells[0].Controls.Add(hl);
Since it's a grid, it's not logical for items to exist within a row outside a cell - then there is no way to know where exactly to display it.
You probably also need to set the NavigateUrl property of the Hyperlink, otherwise it does not know where to navigate e.g.
hl.NavigateURL = "https://www.google.com"
here is my code
after button 2 click event it is creating the dropdown in table rows but when I try to save by button 1 click event it just disappear. I have not find any solution regarding this. I have used find control view State etc but it's not helping.
I want to store selected values of dropdown after button_1 click event starts.
public partial class StudentClassSectionMapping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ClassCode.Enabled = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
UpdateModalShowFlag.Value = "true";
Check.Value = "true";
CreateTableRows();
}
private void CreateTableRows()
{
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
ClassMaster.ClassMasterForm classCode = Schoolclasses.GetInfo(h);
ClassCode.Text = classCode.cCode;
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allSectionsInClass = StudentsClassSectionMapping.GetSectionsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
DropDownList t = new DropDownList();
t.Items.Add("No Section");
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm sectionList in allSectionsInClass)
{
t.Items.Add(sectionList.ssSection);
t.Items[t.Items.Count - 1].Value = sectionList.ssSectionID.ToString();
}
t.Attributes.Add("class", "form-control");
t.ID = studentList.ssStudentId.ToString();
cell1.Text = studentList.ssName;
cell2.Text = studentList.ssRegistrationNumber;
cell3.Controls.Add(t);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
Table1.Rows.Add(row);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTableRows();
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
DropDownList d = Table1.FindControl(studentList.ssStudentId.ToString()) as DropDownList;
if (d != null)
{
if (d.SelectedIndex != 0)
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = studentList.ssStudentId;
studentSectionMapping.ssStudentId = long.Parse(d.SelectedItem.Value);
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
else
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = 0;
studentSectionMapping.ssStudentId = 0;
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
}
}
}
It get vanished/disappear because you added it dynamically on page. If you want it back or want to reserver control which is dynamically created you need to recreate again and need to add dynamically.
Here is good example of how you can do it : How to create controls dynamically in ASP.NET and retrieve values from it
I want to add some checkboxes at the beginning of every row in a table in the page_load: (I add them in a asp:placeholder)
protected void Page_Load(object sender, EventArgs e)
{
Table dtTable = new Table();
TableHeaderRow dtHeaderRow = new TableHeaderRow();
TableHeaderCell dtHeaderCheckbox = new TableHeaderCell();
dtHeaderCheckbox.Controls.Add(dtHeaderCkBox);
dtHeaderRow.Cells.Add(dtHeaderCheckbox);
foreach (DataColumn col in _ds.Tables[0].Columns)
{
TableHeaderCell dtHeaderCell = new TableHeaderCell();
dtHeaderCell.Text += col.ColumnName;
dtHeaderRow.Cells.Add(dtHeaderCell);
}
dtTable.Rows.Add(dtHeaderRow);
TableRow row;
for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
{
row = new TableRow();
TableCell dtCell = new TableCell();
CheckBox ckBox = new CheckBox();
ckBox.ID = "chkBox_" + _ds.Tables[0].Rows[i]["IDENTIFIER"].ToString();
ckBox.AutoPostBack = false;
ckBox.EnableViewState = false;
dtCell.Controls.Add(ckBox);
row.Cells.Add(dtCell);
for (int j = 0; j < _ds.Tables[0].Columns.Count; j++)
{
TableCell cell = new TableCell();
cell.Text = _ds.Tables[0].Rows[i][j].ToString();
row.Cells.Add(cell);
}
dtTable.Rows.Add(row);
}
phUnconfirmedDiv.Controls.Add(dtTable);
}
The problem is now, when the user press a submit button(and postback), I don't have access to my checkboxes:
protected void btnAccept_OnClick(object sender, EventArgs e)
{
List<CheckBox> chkList = new List<CheckBox>();
foreach (Control ctl in form1.Controls)
{
if (ctl is CheckBox)
{
if (ctl.ID.IndexOf("chkBox_") == 0)
{
chkList.Add((CheckBox)ctl);
}
}
}
ScriptManager.RegisterStartupScript(this, GetType(), "event", "alert('" + chkList.Count + "');", true);
}
Dynamically generated controls lost their state once they are rendered on view. And for you, to access them again in your code-behind, when your postbacks, you will have to re-create them and after that you will be able to manipulate them.
As far as getting the checked values of the checkboxes is concerned, you could try something like this. This might not be exact, should give an idea though.
This would be your check-box :
<input type="checkbox" id="yourId" name="selectedIds" value="someValue"/>
In your codebehind :
value = Request.Form["selectedIds"];
Hope this helps.
I now managed to solve this problem. Thanks all for your tips!
All checkboxes that are checked are sent through the postback. So the "easiest" way is to search for all parameters, sent in postback, that are beginning like "chkBox_" and then save them in a list/array. So I know which data should be updated in my database:
protected void btnAccept_OnClick(object sender, EventArgs e)
{
List<String> chkList = new List<String>();
// All checked checkboxes are sent via the postback. Save this parameters in a list:
foreach (string s in Request.Params.Keys)
{
if (s.ToString().IndexOf("chkBox_") == 0)
{
chkList.Add(s.ToString());
}
}
Is autopostback set to true on the user interface controls for the button? ei:
<telerik:RadButton runat="server" ID="rBtnRelease" Text="Release" Width="100px" OnClick="rBtnRelease_Click" AutoPostBack="False"/>
That's usually the common mistake when one tries to get data back and forth between the client and the server side.
I have a GridView which holds user data. When the Page_Load Method is called, I get data using a DataTable and then bind it to the GridView. At the end of each row, I have added a CheckBox. This CB is used as a pointer for which entity the user wants to edit.
My problem is the Check_Changed Event of the CheckBoxes. I do not know how to add a handler if the control is generated programmatically. I also need the index of the row (a field value is also possible, but the column header and the column itself are hidden).
foreach (GridViewRow gvr in grdMitgliedsliste.Rows)
{
//add checkbox for every row
TableCell cell = new TableCell();
CheckBox box = new CheckBox();
cell.Controls.Add(box);
gvr.Cells.Add(cell);
//Hide columns for userid, status, etc.
gvr.Cells[0].Visible = false;
gvr.Cells[3].Visible = false;
gvr.Cells[4].Visible = false;
gvr.Cells[5].Visible = false;
gvr.Cells[8].Visible = false;
gvr.Cells[9].Visible = false;
}
I have already tried implementing the handler from here, but it gives me no index argument so the program cannot determine in which row the checkbox was checked.
protected void Page_Load(object sender, EventArgs e)
{
List<string> names = new List<string>();
names.Add("Jhonatas");
this.GridView1.DataSource = names;
this.GridView1.DataBind();
foreach (GridViewRow gvr in GridView1.Rows)
{
//add checkbox for every row
TableCell cell = new TableCell();
CheckBox box = new CheckBox();
box.AutoPostBack = true;
box.ID = gvr.Cells[0].Text;
box.CheckedChanged += new EventHandler(box_CheckedChanged);
cell.Controls.Add(box);
gvr.Cells.Add(cell);
}
}
void box_CheckedChanged(object sender, EventArgs e)
{
string test = "ok";
}
TableCell cell = new TableCell();
CheckBox box = new CheckBox();
box.Check += new EventHandler(Checked_Changed);
cell.Controls.Add(box);
gvr.Cells.Add(cell);
sorry, im allready about to drive home so its just an fast answer.
mabye you have to correct the event after box."event" ...
You should go this way:
first of all when you are generating the checkbox
CheckBox box = new CheckBox();
box.AutoPostBack=true;
provide an id to the checkbox as
box.ID=Convert.toString(Session["Count"]);
do initialize the "Count" when the page loads in the session.
also increment the "Count" everytime you add a new checkbox.
secondly, define the event handler for your dynamic check box like this:
box.CheckedChange += MyHandler;
and define the MyHandler
protected void MyHandler(object sender, EventArgs e)
{
//Do some stuff
}
now you may get the id for the checkbox from which the event has been fired inside the MyHandler, which will actually be the row number.
CheckBox cb = (CheckBox)sender;
string id = cb.ID;
I am creating a gridview dynamically with a ButtonField and several BoundFields. ButtonField button type is LinkButton. If i run it the buttonclick triggers a post back but rowCommand is not triggered. It is not triggered even if i use AutogenerateSelectButton. The event is dyanamically bound. Code As follows:
protected void B_Search_Click(object sender, EventArgs e) //Search buttonclick that creates and displays the gridview
{
gd = getGridView(); //defines the gridview with columns and buttonfield
gd.DataSource = executeAdvanceSearch(); //retrieves data from DB as Dataset
gd.DataBind();
gd.RowCommand += new GridViewCommandEventHandler(gdView_RowCommand); //Rowcommand event binding
PlaceHolder1.Controls.Add(gd);
}
protected void gdView_RowCommand(object sender, GridViewCommandEventArgs e) //not getting triggered on postback
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gdView = (GridView)sender;
if (e.CommandName == "IDClick")
{
//Do something
}
}
private GridView getGridView()
{
GridView gdView = new GridView();
gdView.AutoGenerateColumns = false;
gdView.AutoGenerateSelectButton = true;
string name;
string[] field = ZGP.BLL.Search.getResultFormat(Convert.ToInt32(DDL_ResultView.SelectedValue), out name); //Ignore. This jst gets columnNames
if (field.Count() != 0)
{
gdView.Columns.Add(getSelectButton()); //Adds linkbutton
foreach (string cName in field) //ignore. This adds columns.
if (!String.IsNullOrEmpty(cName))
{
gdView.Columns.Add(GV_DataColumn.getGridViewColumn((DataColumnName)Enum.Parse(typeof(DataColumnName), cName))); //Ignore. adds columns
}
}
return gdView;
}
private ButtonField getSelectButton()
{
ButtonField _bf = new ButtonField();
_bf.ButtonType = ButtonType.Link;
_bf.HeaderText = "ID";
_bf.DataTextField = "ID";
_bf.CommandName = "IDClick";
return _bf;
}
Thanks for the help.
if (e.CommandName=="CommandName")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
string boundFieldText= row.Cells[0].Text;
}
You'll need to create the grid view on each postback.