Code Behind Gridview's RowDataBound event - asp.net

I have created a gridview in code behind (as in its not physically present on the page). I want to know how to call it's rowdatabound event - as data is being bound to it. There happens to be a Gv.RowDataBound function, but how do I use it?
(I want the same functionality as what the asp:gridview control has for its onrowdatabind attribute...)
GridView Gv = new GridView();
Gv.AutoGenerateColumns = false;
BoundField one = new BoundField();
one.DataField = "one";
one.HeaderText = "One";
Gv.Columns.Add(one);
BoundField two = new BoundField();
one.DataField = "two";
one.HeaderText = "Two";
Gv.Columns.Add(two);
//dt is a datatable with some data
Gv.DataSource = (dt);
Gv.DataBind();

Set the eventhandler for the gridview using:
Gv.RowDataBound += new GridViewRowEventHandler(Gv_RowDataBound);
Then create its own eventhandler
void Gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Do whatever you want in here.
}

To achieve this in VB, use this:
AddHandler Gv.RowDataBound, AddressOf Gv_RowDataBound

Related

Capturing the value of dynamically created TextBox and DropDownList in ASP.NET

I am stuck in an issue, tried googling but could not find any solution.
I have created controls dynamically in Page_Load and I have a static button.
When the button is clicked, I need to capture user entry in those controls.
Now when I am trying to access the control using its unique id, error is being returned as the control is not available at runtime. :(
For loop - starts
if (dr["Type"].ToString().Trim() == "DropDown")
{
DropDownList ddl = new DropDownList();
ddl.Id = "ddl" + Convert.ToString(Counter);
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = ds1;
ddl.DataBind();
ddl.EnableViewState = true;
cell.Controls.Add(ddl);
}
else if (dr["QuestionType"].ToString().Trim() == "TextBox")
{
TextBox txt = new TextBox();
txt.ID = "txt" + Convert.ToString(Counter);
txt.EnableViewState = true;
cell.Controls.Add(txt);
}
row.Cells.Add(cell);
table.Rows.Add(row);
Even if i do a FindControl in Btn_click function, it says that the panel has 0 controls.
var textbox = (TextBox)pnlMidTermFeedback.FindControl("txt5");
textbox is always NULL, although I have a control txt5. I can see it when I do a F12.
Please help.
Dynamically created controls must be recreated on every postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set values and properties of controls specified in markup
...
}
// Create new controls and add them to the panel
...
}
They will then be available in the button event handler, and contain the data entered by the user.

linkButton Click Event in Grid View not firing when adding though Bound Fields in a loop in GridView

Hi,Here i am trying to implement the linkButton click event in a
gridview through code behind using the BoundField Class in gridview.
when i trying to add the individual BoundField values Directly to grid
as a column in page_Load and binding the linkbutton in
RowDataBoundEvent of the row of cell with linkbutton click event, it
is firing the linkButton Click event well with the following code.
protected void Page_Load(object sender,EventArgs e)
{
BoundField bfield = new BoundField();
bfield.HeaderText = "EmpName";
bfield.DataField = "EmpName";
gridView.Columns.Add(bfield);
BoundField bfield1 = new BoundField();
bfield1.HeaderText = "Monday";
bfield1.DataField = "Monday";
gridView.Columns.Add(bfield1);
}
and in on RowDataBound Event i have wrote
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkViews = new LinkButton();
lnkViews.ID = "lnkViews";
lnkViews.Text = (e.Row.DataItem as DataRowView).Row["Monday"].ToString();
lnkViews.Click += new EventArgs(linkButton_ClickAction);
e.Row.Cells[2].Controls.Add(lnkViews);
}
}
protected void linkButton_ClickAction(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[0].Text; this.ModalPopupExtender1.Show();
}
But when i trying to add the above BoundFields by looping based on the
table columns count like this, in page_Load event, the event is not
firing.
protected void Page_Load(object sender,EventArgs e)
{
DataTable dtTable = new DataTable();
dtTable= BindGrid();
BoundField boundField;
for (int i = 0; i < dtTable.Columns.Count; i++)
{
string ColumnValue = dtTable.Columns[i].ColumnName;
boundField = new BoundField();
boundField.HeaderText = ColumnValue;
boundField.DataField = ColumnValue;
gridView.Columns.Add(boundField);
}
}
when we creating the BoudnField event using the above code in a loop
based on dataSource columns count, it doesn't firing linkbutton event. why?
as per my understanding you are trying to form grid dynamically.
One thing is bound fields will not support for bubbled events. So better replace them with template fields that will meets your requirement.
You need to assign click event in InstantiateIn method by defining ITemplate interface.
OnRowDataBound event doesn't comes into picture.
below is example for your reference.
http://forums.asp.net/t/1001702.aspx

how to edit the gridview programatically in asp.net?

GridView gv = new GridView();
BoundField farmername = new BoundField();
farmername.HeaderText = "Farmer Name";
farmername.DataField = "farmername";
gv.Columns.Add(farmername);
BoundField villagename = new BoundField();
villagename.HeaderText = "Village Name";
villagename.DataField = "village";
gv.Columns.Add(villagename);
BoundField feedtype = new BoundField();
feedtype.HeaderText = "Feed Type";
feedtype.DataField = "feedtype";
gv.Columns.Add(feedtype);
BoundField bf50kg = new BoundField();
bf50kg.HeaderText = "50 Kg Bags";
bf50kg.DataField = "noof50kgsbags";
gv.Columns.Add(bf50kg);
CommandField cf = new CommandField();
cf.ButtonType = ButtonType.Button;
cf.ShowCancelButton = true;
cf.ShowEditButton = true;
gv.Columns.Add(cf);
gv.RowEditing += new GridViewEditEventHandler(gv_RowEditing);
gv.RowUpdating += new GridViewUpdateEventHandler(gv_RowUpdating);
gv.RowCancelingEdit += new GridViewCancelEditEventHandler(gv_RowCancelingEdit);
gv.AutoGenerateColumns = false;
gv.ShowFooter = true;
gv.DataSource = dtIndentDetails;
gv.DataBind();
When I clicked on edit button its not spliting into update, Cancel buttons . How can I do this with command field .If I add gridview in aspx page, its splitting to update and cancel
Try the following code:
protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gv = (GridView)sender;
// Change the row state
gv.Rows[e.NewEditIndex].RowState = DataControlRowState.Edit;
}
Tried your code and found it working.
Take care of below points:
1.) The Code creating GridView (and all fields ) should be executed every time. Means remove any !IsPostback condition from this code, If present any.
2.) In your RowEditing event of your gridview set the editindex and rebind the gridview.
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gv = sender as GridView;
gv.EditIndex = e.NewEditIndex;
gv.DataBind();
}

gridview data is null in when passing gridview to another method

I bind the gridview in the following event:(subjectdropdown_SelectedIndexChanged)
I send the gridview in the following event as a parameter to another method:Button1_click event.
protected void subjectdropdown_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable getmarkfdb = inter.getmarksfromdatabaseothers(comp);
if (getmarkfdb.Rows.Count > 0)
{
TemplateField lable1 = new TemplateField();
lable1.ShowHeader = true;
lable1.HeaderText = "AdmissionNumber";
lable1.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "AdmissionNumber", "AdmissionNumber", "Label");
studmarkgrid.Columns.Add(lable1);
TemplateField label2 = new TemplateField();
label2.ShowHeader = true;
label2.HeaderText = "RollNumber";
label2.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "RollNumber", "RollNumber", "Label");
studmarkgrid.Columns.Add(label2);
TemplateField label3 = new TemplateField();
label3.ShowHeader = true;
label3.HeaderText = "Name";
label3.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "Name", "Name", "Label");
studmarkgrid.Columns.Add(label3);
TemplateField extmep = new TemplateField();
extmep.ShowHeader = true;
extmep.HeaderText = "ExternalMark";
extmep.ItemTemplate = new gridviewtemplate(DataControlRowType.DataRow, "ExternalMark", "ExternalMark", "TextBox");
studmarkgrid.Columns.Add(extmep);
studmarkgrid.DataSource = getmarkfdb;
studmarkgrid.DataBind();
}
}
In the TextBoxTemplate column of the gridview I fill the Mark for student and in the following event i send the gridview to insertstumark method for read data from gridview and save into database. but in the insertstumark method gridview rows data are null.
protected void Button1_Click(object sender, EventArgs e)
{
comp.ACADAMICYEAR = acyeardropdown.SelectedItem.Text;
comp.MEDIUM = mediumdropdown.SelectedItem.Text;
string clas = classdropdown.SelectedItem.Text;
string[] cs = clas.Split('-');
comp.CLASSNAME = cs[0].ToString();
comp.SECTIONNAME =Convert.ToChar(cs[1].Trim().ToString());
comp.EXAMNAMES = examnamedropdown.SelectedItem.Text;
comp.SUBJECTID = subjectdropdown.SelectedValue.ToString();
// studmarkgrid.DataBind();
// System.Web.UI.WebControls.GridView grid = studmarkgrid;
// System.Web.UI.WebControls.GridView grid = ViewState["stdmarkgrid"] as System.Web.UI.WebControls.GridView;
DataTable studtable = null;
// System.Web.UI.WebControls.GridView grid = (System.Web.UI.WebControls.GridView)ViewState["stdmarkgrid"];
bool studm = inter.inserstumark(comp,stumarkgrid);
}
What is the problem. I tried to stored the gridview in viewstate. but in the following line it through the error. How to solve this problem?
System.Web.UI.WebControls.GridView grid = ViewState["stdmarkgrid"] as System.Web.UI.WebControls.GridView;
A lot of times, if the data is bound to the GridView too late in the Page Lifecycle, the GridView is rendered, and the data forgotten, so at the next PostBack, you won't have access to the GridView's underlying data source.
That looks like what's happening here. Just save the result of getmarksfromdatabaseothers to ViewState so you can access it again as necessary.

grid view databound event

how data bound event of grid view is used and how is it called could somebody elaborate a bit on this please
i bind gridview on button click like this
DataTable dt = placedStudentManager.GetPlacedStudentList(sb, passoutYear, courseList);
if (dt != null && dt.Rows.Count != 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
ViewState["dt"] = dt;
}
and whenever i need it again to bind i use view state like this, but can data bound event be any use instead of having view state can i use directly data bound event or some good alternate exist please let me know
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
// StringBuilder str=(StringBuilder)ViewState["chk"];
//foreach (GridViewRow row in GridView1.Rows)
//{
//}
}
The DataBound event fires when all the databinding for the Gridview is finished, so that you could do, say, subtotals of all the rows in the Gridview at that point as you know there aren't going to be any more rows in the view. You call it like any other event, set the attribute in your markup and put the code in your code-behind:
<asp:gridview id="Gridview1" runat="server" ondatabound="Gridview1_DataBound"
...
</asp:gridview>
private void Gridview1_DataBound(EventArgs e)
{
...
}
Could you use it in what you're doing? Possibly - can you put a bit more detail in your question about the way you're thinking?

Resources