how to edit the gridview programatically in asp.net? - 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();
}

Related

Programmatically add OnRowDelete to a GridView

I'm programatically generating GridViews, each GridView has a CommandField with a delete button. How do I programatically add OnDeletingRow so that a function is called when the delete button with the GridView is clicked?
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.ID = "GridView_" + selectedId;
gv.DataKeyNames = new string[] {"id"};
gv.AllowPaging = false;
gv.CellPadding = 3;
gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);
CommandField commandfieldDeallocate = new CommandField();
commandfieldDeallocate.HeaderText = "DELETE NUMBER";
commandfieldDeallocate.ShowDeleteButton = true;
commandfieldDeallocate.DeleteText = "DELETE";
gv.Columns.Add(commandfieldDeallocate);
In C#, you can do it this way:
gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);
void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// Perform deletion
}

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

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.

Capture DropDownList Index Change event inside of grid View

I am trying to capture the SelectedIndexChanged event for a drop down list I have put inside of a gridview control. It posts back fine, but does not go into my SelectedIndexChanged event handler. Here is my code
DropDownList myddl;
protected void Page_Load(object sender, EventArgs e)
{
this.myGridview.RowDataBound += new GridViewRowEventHandler(myGridview_RowDataBound);
myddl = new DropDownList();
myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
if (!Page.IsPostBack)
{
List<Team> teams = giveMeTeams();
this.myGridview.DataSource = teams;
this.myGridview.AutoGenerateColumns = false;
BoundField col1 = new BoundField();
col1.DataField = "Name";
this.myGridview.Columns.Add(col1);
BoundField col2 = new BoundField();
col2.DataField = "Sport";
this.myGridview.Columns.Add(col2);
BoundField col3 = new BoundField();
col3.DataField = "Status";
this.myGridview.Columns.Add(col3);
this.myGridview.DataBind();
}
}
void myGridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
myddl = new DropDownList();
myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
List<string> items = new List<string>();
items.Add("good");
items.Add("bad");
myddl.DataSource = items;
myddl.AutoPostBack = true;
myddl.DataBind();
e.Row.Cells[2].Controls.Add(myddl);
}
void myddl_SelectedIndexChanged(object sender, EventArgs e)
{
string temp = "In Here"; //neve hits this code
}
private List<Team> giveMeTeams()
{
Teams teams = new Teams();
teams.Add(new Team("RedWings", "Hockey", "good"));
teams.Add(new Team("Lions", "Football", "bad"));
teams.Add(new Team("Packers", "Football", "good"));
return teams;
}
Any help is greatly appreciated.
Thanks,
Edited based on Comments
I have tried as you suggested...and am still not capturing the post back. here is my new code
void myGridview_RowCreated(object sender, GridViewRowEventArgs e)
{
DropDownList myddl = new DropDownList();
myddl = new DropDownList();
myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
myddl.ID = "MyID" + e.Row.RowIndex.ToString();
e.Row.Cells[2].Controls.Add(myddl);
}
void myGridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList myddl = e.Row.FindControl("MyID" + e.Row.RowIndex.ToString()) as DropDownList;
//myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
List<string> items = new List<string>();
items.Add("good");
items.Add("bad");
myddl.DataSource = items;
myddl.DataMember = "Status";
myddl.AutoPostBack = true;
myddl.DataBind();
e.Row.Cells[2].Controls.Add(myddl);
}
it is still not going into my myddl_SelectedIndexChanged() eventhandler.
Create that Dropdownlist in RowCreated of the Grid and assign an ID to it. Get the refrence to these Dropdowns in RowDataBound via e.Row.FindControl("MyDropdownlistID") and bound them to the Datasource. Create distinct Dropdownlist instances instead of referencing always the same

Code Behind Gridview's RowDataBound event

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

Resources