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
}
Related
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();
}
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.
Hi i added template field dynamically to gridview by implementing ITemplate interface.
The template field contains some controls like label and textboxes. how do i get these controls in row databound event.
I am not able to get when i do gridviewrow.findcontrol("id") as i do normally when we add templatefield from aspx page.
The way i added template field is like this
public class CustomGridViewColumn : ITemplate
{
ListItemType _liType;
string _columnName;
public CustomGridViewColumn(ListItemType type, string column)
{
_liType = type;
_columnName = column;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_liType)
{
case ListItemType.Header:
Label lblHeader = new Label();
lblHeader.Text = _columnName;
container.Controls.Add(lblHeader);
break;
case ListItemType.Item:
Label lblItem = new Label();
lblItem.DataBinding += new EventHandler(lbl_DataBinding);
lblItem.ID = "lbl" + _columnName;
lblItem.ClientIDMode = ClientIDMode.Predictable;
container.Controls.Add(lblItem);
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(ddl_DataBinding);
ddl.ID = "ddl" + _columnName;
ddl.Visible = false;
container.Controls.Add(ddl);
break;
}
}
}
Now i want access the label and dropdown which i have added using this code.
when i do gridviewrow.findcontrol("id") i am not getting them.
Can any one please help me.
I am geeting when i go through all the rows and try to find but
i have a check box in a row when i select it all labels should diappear and ddls dhould appear
for this i am using the follwoing code.
protected void chkEdit_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkEditTest = (CheckBox)sender;
GridViewRow grow = (GridViewRow)chkEditTest.NamingContainer;
DropDownList ddl = (DropDownList)grow.FindControl("ddl");
Label lbl= (Label)grow.FindControl("lbl");
}
when i do this i am not able to get the controls.
it seems like controls are disapppearing on postback..
This is what I came up with and I can able to get the control reference in the code behind.
public class CustomGridViewColumn : ITemplate
{
ListItemType _liType; string _columnName;
public CustomGridViewColumn(ListItemType type, string column)
{
_liType = type;
_columnName = column;
}
void ITemplate.InstantiateIn(Control container)
{
switch (_liType)
{
case ListItemType.Header:
Label lblHeader = new Label();
lblHeader.Text = _columnName;
container.Controls.Add(lblHeader);
break;
case ListItemType.Item:
Label lblItem = new Label();
lblItem.DataBinding += new EventHandler(lblItem_DataBinding);
lblItem.ID = "lbl" + _columnName;
lblItem.ClientIDMode = ClientIDMode.Predictable;
container.Controls.Add(lblItem);
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(ddl_DataBinding);
ddl.ID = "ddl" + _columnName;
ddl.Visible = false;
ddl.DataSource = new string[] { "Hello", "World" };
container.Controls.Add(ddl);
break;
}
}
void ddl_DataBinding(object sender, EventArgs e)
{
}
void lblItem_DataBinding(object sender, EventArgs e)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
DataRow oItem = dt.NewRow();
oItem[0] = "Deepu";
dt.Rows.Add(oItem);
oItem = dt.NewRow();
oItem[0] = "MI";
dt.Rows.Add(oItem);
GridView gv = new GridView();
gv.ID = "myGridView";
gv.AutoGenerateColumns = false;
BoundField nameColumn = new BoundField();
nameColumn.DataField = "Name";
nameColumn.HeaderText = "Name";
gv.Columns.Add(nameColumn);
TemplateField TmpCol = new TemplateField();
TmpCol.HeaderText = "Template Column";
gv.Columns.Add(TmpCol);
TmpCol.ItemTemplate = new CustomGridViewColumn(ListItemType.Item, "TEST");
gv.DataSource = dt;
gv.DataBind();
Form.Controls.Add(gv);
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView gv = Form.FindControl("myGridView") as GridView;
foreach (GridViewRow item in gv.Rows)
{
var ddl = item.FindControl("ddlTest") as DropDownList;
if (ddl != null)
{
ddl.Visible = true;
}
var lbl = item.FindControl("lbl") as Label;
if (lbl != null)
{
lbl.Text = "hello";
}
}
}
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
Thanks
Deepu
Can you try using row index of GRIDVIEW control
var rowIndex = int.Parse(e.CommandArgument)
GridView1.Rows[rowIndex].FindControl("id")
Also refer
http://forums.asp.net/t/998368.aspx/1
http://www.codeproject.com/Articles/12021/Accessing-the-different-controls-inside-a-GridView
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.aspx
Thanks
Deepu
i created gridview dynamically,
which consists of Textboxes and buttonfield, on row command event of the gridview i want to access the content of textbox.
i am not able to access the textbox
here is my code
protected void FillGridListTollCollection()
{
TollCollectionBLLC tollcollectionBLLC = new TollCollectionBLLC();
dataTable = tollcollectionBLLC.GetTollCollectionDetailsBLLC(187, 1, 1, "10/10/2011");
//put the gridview into the placeholder to get the values of textboxes in gridview
PlaceHolder1.Controls.Add(GridListTollColletion);
foreach (DataColumn col in dataTable.Columns)
{
if (col.ToString() == "TollCollID")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollCollID";
bField.DataField = "TollCollID";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollAmtApplicable")
{
BoundField bField = new BoundField();
bField.HeaderText = "TollAmtApplicable";
bField.DataField = "TollAmtApplicable";
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "TollCollDesc")
{
BoundField bField = new BoundField();
bField.HeaderText = "Transaction Types";
bField.DataField = "TollCollDesc";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString() == "Total")
{
BoundField bField = new BoundField();
bField.HeaderText = "Total";
bField.DataField = "Total";
GridListTollColletion.Columns.Add(bField);
continue;
}
if (col.ToString().Contains("Rate"))
{
BoundField bField = new BoundField();
bField.HeaderText = col.ToString();
bField.DataField = col.ToString();
bField.Visible = false;
GridListTollColletion.Columns.Add(bField);
continue;
}
//Declare the bound field and allocate memory for the bound field.
TemplateField tfield = new TemplateField();
//Initalize the DataField value.
tfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
tfield.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
tfield.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
tfield.ItemStyle.VerticalAlign = VerticalAlign.Middle;
//Initialize the HeaderText field value.
tfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
GridListTollColletion.Columns.Add(tfield);
}
protected void GridListTollColletion_RowCommand(object sender, GridViewCommandEventArgs e)
{
int tempCarCount = 0;
// here i am getting exception
int.TryParse( ( (TextBox)GridListTollColletion.Rows[Convert.ToInt32(e.CommandArgument)].Cells[Convert.ToInt32(e.CommandArgument)].Controls[3]).Text , out tempCarCount);
}
public class GridViewTemplate : ITemplate
{
//A variable to hold the type of ListItemType.
ListItemType _templateType;
//A variable to hold the column name.
string _columnName;
//Constructor where we define the template type and column name.
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;
//Stores the column name.
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label(); //Allocates the new label object.
lbl.Text = _columnName; //Assigns the name of the column in the lable.
container.Controls.Add(lbl); //Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox(); //Allocates the new text box object.
tb1.Width = 60;
tb1.Height = 22;
tb1.MaxLength = 50;
tb1.ID = "v";
//Creates a column with size 4.
tb1.DataBinding += new EventHandler(tb1_DataBinding); //Attaches the data binding event.
tb1.Columns = 7;
container.Controls.Add(tb1);
//Adds the newly created textbox to the container.
break;
case ListItemType.EditItem:
//As, I am not using any EditItem, I didnot added any code here.
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
public IOrderedDictionary ExtractValues(Control container)
{
OrderedDictionary dict = new OrderedDictionary();
if (_templateType == ListItemType.Item)
{ string value = ((TextBox)container.FindControl("tb1" + _columnName)).Text;
dict.Add(_columnName, value); }
return dict;
}
void tb1_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}
public GridViewTemplate()
{
//
// TODO: Add constructor logic here
//
}
}
The template is applied statically. So, you wont be able to access the control as you are trying to do.
Try using -
var textbox = GridListTollColletion.FindControl(<yourtextbox>);
Is it not convenient if you bind these added controls on GridView.RowDataBound event.
Check this BindData to ITemplate for GridView in code behind
If you are following this MSDN Article How To: Create ASP.NET Web Server Control Templates Dynamically to take idea about this then check this code snippet.
static void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
RepeaterItem ri = (RepeaterItem)ph.NamingContainer;
Int32 item1Value = (Int32)DataBinder.Eval(ri.DataItem, "CategoryID");
String item2Value = (String)DataBinder.Eval(ri.DataItem, "CategoryName");
((Label)ph.FindControl("item1")).Text = item1Value.ToString();
((Label)ph.FindControl("item2")).Text = item2Value;
}
It have Item_DataBinding a static method. you are setting up this stuff statically, so check this article to improve your code.
In Edit Template i suggest you to use RowBound Event to handle for these template controls.. there you can easily access them.
I am able to create BoundFields and Footer-rows dynamically like this in my GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateGridView();
}
}
private void CreateGridView()
{
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
int colCount = 1;
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
//boundField.FooterText = "---";
if (colCount == 3 || colCount == 5)
{
boundField.ReadOnly = true;
}
GridView1.Columns.Add(boundField);
colCount++;
}
GridView1.ShowFooter = true;
GridView1.DataSource = dataTable;
GridView1.DataBind();
GridViewRow footerRow = GridView1.FooterRow;
Button b = new Button();
b.Text = "Add New";
int i = 0;
footerRow.Cells[i].Controls.Add(b);
foreach (DataColumn c in dataTable.Columns)
{
++i;
TextBox tb = new TextBox();
footerRow.Cells[i].Controls.Add(tb);
}
}
....................................
....................................
....................................
}
But the problem is, when I click the "Add New" - button, it disappears instantly. And, also I am unable to add any event handler to it. Or intercept its actions like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//We can get cell data like this
string id = selectedRow.Cells[1].Text;
string isbn = selectedRow.Cells[2].Text;
//This is necessary to GridView to be showed up.
CreateGridView();
}
else if (e.CommandName == "Update")
{
LinkButton updateButton = (LinkButton)e.CommandSource;
DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;
GridViewRow gvr = (GridViewRow)dcfc.Parent;
//The update...................
//Update grid-data to database
UpdateDataInTheDatabase(gvr.Cells[1].Controls);
//Grid goes back to normal
GridView1.EditIndex = -1;
//This is necessary to GridView to be showed up.
CreateGridView();
}
}
One more thing, I have seen some solutions that suggests to handle the GridView's rowBound event. But I need to do it from within Page_load event handler, or in, GridView1_RowCommand event handler.
Dynamically created controls mus be re-created on every postback. Your "Add New" button causes a postback so the dynamically created footer disappears. Is there a reason this grid has to be created dynamically? From the code you posted it appears that you could do this in markup instead. If not, you'll have to re-create the dynamic controls on every postback.
Edited to add:
I played with this a little bit and what's below works in that the grid doesn't disappear and events are handled, but it doesn't actually do anything. Hope this helps.
Markup:
<p><asp:Literal ID="Literal1" runat="server" /></p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}
Move your code from Page_Load to Page_Init. Things added in the Page_Load last only for the lifecycle of one postback.
You'd then be able to add eventhandlers, intercept events etc.