Dropdown Save in a gridview - asp.net

I have a GRID that consist of columns that are populated and recently I have added some drop down columns as well to the grid. My drop down is populating with the options from the backend, but now I need to save those answers to the page itself, so the user can see it on the screen next time they arrive on the page.
GRID
protected void gvViolationsCited_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
{
TableCell idCell = GridViewFunctions.FindCellByDataField(e.Row, "ID");
idCell.Visible = false;
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton lb = (ImageButton)e.Row.FindControl("lbShowModalDialog");
long id = long.Parse(idCell.Text);
DropDownList hpvcriteria = (DropDownList)e.Row.FindControl("hpvcriteria");
hpvcriteria.DataSource = LookupDataLoaderService.Instance.LoadLookupData(LookupTables.HPV_VIOLATION_CODE);
hpvcriteria.DataBind();
}
}
}
private void PopulateViolationGrid(long caseID)
{
IList<EnforcementViolation> enforcementViolations = LovService.Instance.GetEnforcementLovList(caseID);
IEnumerator<EnforcementViolation> evEnumerator = enforcementViolations.GetEnumerator();
while (evEnumerator.MoveNext())
{
EnforcementViolation ev = evEnumerator.Current;
//txtOtherDocsViolated.Text += ev.Permit + " ";
}
gvViolationsCited.DataSource = GridViewFunctions.GenericListToDataTable<EnforcementViolation>(enforcementViolations);
gvViolationsCited.DataBind();
upnlViolationsCited.Update();
evEnumerator.Dispose();
}

Related

how to previous selected item remove in dropdown when click on add button in GirdView in Asp.Net

How to remove last row selected item in dropdown add button is clicked gridview asp.net.
GridViewRow gvrow = (GridViewRow)((Control)e.CommandSource).NamingContainer;
if (e.CommandName == "Add")
{
ddt = CreateDt();
int j = 0;
foreach (GridViewRow gr in GvPatientAccomDtls.Rows)
{
ddt.Rows.Add();
ddt.Rows[j]["TreatmentCode"] = ((DropDownList)gr.FindControl("ddlTreatment")).SelectedValue;
ddt.Rows[j]["Days"] = ((TextBox)gr.FindControl("txtDays")).Text;
ddt.Rows[j]["Cost"] = ((TextBox)gr.FindControl("txtCost")).Text;
j++;
}
ddt.Rows.Add();
GvPatientAccomDtls.DataSource = ddt;
GvPatientAccomDtls.DataBind();
}
you can handle with RowDataBound Event
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var thisRow = (DataRowView)e.Row.DataItem;
var source = thisRow.DataView;
var lastRowIndex = e.Row.DataItemIndex -1;
DataRowView lastRow = null;
var ddl = (DropDownList)e.Item.FindControl("ddl");
DropDownList ddlLast = null;
if(lastRowIndex>=0){
lastRow = source[lastRowIndex];
ddlLast = (DropDownList)((GridView)sender).Rows[lastRowIndex].FindControl("ddl");
//remove the items of this ddl according to the items of the last dll
}
}
}

How to access dynmaically added Textbox values ASP.Net

I have a gridview placed on a ASP.Net WebSite, and added a column dynamically like this:
protected void gvGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (DataControlRowType.DataRow == e.Row.RowType && e.Row.RowState != DataControlRowState.Edit &&
(e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
TextBox tb = new TextBox();
tb.ID = "tb";
tb.Attributes.Add("runat", "server");
int i = e.Row.Cells.Count;
i = i - 1;
e.Row.Cells[i].Controls.Add(tb);
}
}
The gridview is populated, and at the end of every row the TextBox is added. When I look at the HTML Code that is delived to the Browser, I can see that the ID of every Textbox is "gv_Items_tb_X" with X being the current row index.
Now I would like to access the content that the user types in the tb on a button click. I tried following code, but it I get an exception becuase the textbox is null.
protected void btn_UpdateCount_Click(object sender, EventArgs e)
{
OI_Data_Service.OI_Data_ServiceClient sc = new OI_Data_Service.OI_Data_ServiceClient();
foreach (GridViewRow row in gv_Items.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
TextBox tb_value = (TextBox)gv_Items.Rows[row.RowIndex].Cells[5].FindControl("gv_Items_tb_" + row.RowIndex);
sc.UpdateItemOnOpening("1", row.Cells[0].Text, tb_value.Text);
}
}
Response.Redirect("~/okay.aspx");
}
Can anyone tell my what I am doing wrong?
Thanks!

how to add footer template dynamically in asp.net

I have created a gridview dynamically. There is template fields described in designing portion. All the columns were created thru code behind as follows. Its works fine. Here I can listed the pages for each rows. But I dont know how to implement the sum of pages in the footer template thru code behind.
TemplateField Pages = new TemplateField();
Pages.HeaderText = "Pages";
Pages.ItemTemplate = new GridViewTemplate_Pages();
gv1.Columns.Add(Pages);
public class GridViewTemplate_Pages : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
Label PagesLabel = new Label();
PagesLabel.DataBinding += new EventHandler(this.PagesLabel_DataBinding);
container.Controls.Add(PagesLabel);
}
void PagesLabel_DataBinding(object sender, EventArgs e)
{
Label lbl1 = (Label)sender;
GridViewRow row = (GridViewRow)lbl1.NamingContainer;
lbl1.Text = DataBinder.Eval(row.DataItem, "PagesReceived").ToString();
}
}
Given ShowFooter="True" in aspx page and RowDataBound written separately. The following code works fine if I given footer template in aspx page but do not know how to get the result in programmatically. Please advice.
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int RowTotalPages = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "PagesReceived"));
TotalPages = TotalPages + RowTotalPages;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label m = (Label)e.Row.FindControl("gv1TotalPages");
m.Text = TotalPages.ToString();
}
}
You can create the footer to a gridview like this.
//Code
GridView gv = new GridView();
gv.RowCreated += delegate(object dsender, GridViewRowEventArgs ge)
{
if (ge.Row.RowType == DataControlRowType.Footer)
ge.Row.Cells[0].Text = "Something";
};
gv.AutoGenerateColumns = false;
gv.ShowFooter = true;
BoundField bf = new BoundField();
bf.HeaderText = "col 1";
bf.DataField = "Length";
gv.Columns.Add(bf);
gv.DataSource = new string[] { "One", "Two", "Three" };
gv.DataBind();
Form.Controls.Add(gv);
This is for the dynamically created gridview and a footer. You can change accordingly.
Its a silly thing. I made it complex. I need the sum of pages in the footer row, then why should I think and confuse about GridViewTemplate and Itemplate class. Simply I added the Total pages in the session and recollect it in the DataControlRowType.Footer. Here is the code:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int RowTotalPages = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "PagesReceived"));
int RowTotalCharges = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ChargesReceived"));
TotalPages = TotalPages + RowTotalPages;
TotalCharges = TotalCharges + RowTotalCharges;
Session.Add("TotalPages", TotalPages.ToString());
Session.Add("TotalCharges", TotalCharges.ToString());
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[4].Text = "Batches Count: " + gv1.Rows.Count.ToString();
e.Row.Cells[5].Text = Session["TotalPages"].ToString();
e.Row.Cells[6].Text = Session["TotalCharges"].ToString();
}
}

How to add an extra row (containing a Button and corresponding event handler) to the GridView

This must be something that a lot of people have done. Basically, it's a custom GridView (i.e. inherited control) with the ability to update all rows at once. I've tried putting the "update all" button in various places (footer, pager, outside the grid), but it looks neatest (to me) when the button is in an extra row as the last row of the GridView.
NB: The pager row is not a suitable place for this button because this custom control could be used in a situation where paging is false. Similarly, the normal footer may be required for some other purpose (e.g. totals).
Here's my code for putting the button in the correct place (with apologies for the terse variables etc.):
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
//Add an extra row to the table...
if (_updateAllEnabled)
{
GridViewRow r = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
Button btn = new Button();
TableCell c = new TableCell();
btn.ID = "UpdateAllButton"; // tried with and without this line
btn.Text = "Update All";
btn.Click += new EventHandler(UpdateAll);
r.Cells.Add(c);
c.Controls.Add(btn);
Table t = this.Controls[0] as Table;
c.ColumnSpan = this.Columns.Count;
t.Rows.Add(r);
}
}
This gives the appearance that I want, but the click event (UpdateAll) does not fire.
I assume that the stuff is being added too late in the life cycle (PreRender), but where else can I do this to ensure that the row is at the end of the GridView? I also thought that there might be trouble identifying the button, so I tried setting the ID. In any case, the ID in the generated HTML looks OK (consistent with "working" buttons in the pager row.
Is there a way for me to achieve this or am I attempting the impossible?
The best place to create your footer-controls is RowCreated since that's early enough in the lifecycle and also ensures that their recreated on every postback:
Footer approach:
protected void Grid_RowCreated(Object sender, GridViewRowEventArgs e) {
if(e.Row.RowType == DataControlRowType.Footer) {
Button btn = new Button();
TableCell c = new TableCell();
btn.ID = "UpdateAllButton";
btn.Text = "Update All";
btn.Click += new EventHandler(UpdateAll);
var firstCell=e.Row.Cells[0];
firstCell.ColumnSpan =e.Row.Cells.Count;
firstCell.Controls.Add(btn);
while(e.Row.Cells.Count > 1)e.Row.Cells.RemoveAt(e.Row.Cells.Count-1);
}
}
Of course you have to set ShowFooter to true:
<asp:GridView ID="GridView1"
ShowFooter="true"
OnRowCreated="Grid_RowCreated"
runat="server"
</asp:GridView>
Pager approach:
In my opinion this is the purpose of the FooterRow. But if you really want to ensure that your Button is in the very last row of a GridView(even below Pager as commented), i would try my next approach.
Here I'm using the pager for your costom control(s) by adding another TableRow to the PagerTable which inherits from Table.
protected void Grid_RowCreated(Object sender, GridViewRowEventArgs e) {
switch(e.Row.RowType){
case DataControlRowType.Pager:
Button btnUpdate = new Button();
btnUpdate.ID = "UpdateButton";
btnUpdate.Text = "Update";
btnUpdate.Click += new EventHandler(UpdateAll);
var tblPager = (Table)e.Row.Cells[ 0 ].Controls[ 0 ];
var row = new TableRow();
var cell = new TableCell();
cell.ColumnSpan = tblPager.Rows[ 0 ].Cells.Count;
cell.Controls.Add(btnUpdate);
row.Cells.Add(cell);
tblPager.Rows.Add(row);
break;
}
}
To ensure that the pager is visible even if only one page is shown(note that the real pager is invisible if PageSize==1):
protected void Grid_PreRender(object sender, EventArgs e){
GridView gv = (GridView)sender;
GridViewRow gvr = (GridViewRow)gv.BottomPagerRow;
if(gvr != null) {
gvr.Visible = true;
var tblPager = (Table)gvr.Cells[ 0 ].Controls[ 0 ];
//hide real pager if unnecessary
tblPager.Rows[ 0 ].Visible = GridView1.PageCount > 1;
}
}
Of course now you have to set AllowPaging=true:
<asp:GridView ID="GridView1"
AllowPaging="true"
PagerSettings-Mode="NumericFirstLast"
OnRowCreated="Grid_RowCreated"
OnPreRender="Grid_PreRender"
OnPageIndexChanging="Grid_PageChanging"
runat="server">
</asp:GridView>
Final approach(working for a custom GridView and all PagerPositions):
public PagerPosition OriginalPagerPosition{
get { return (PagerPosition)ViewState[ "OriginalPagerPosition" ]; }
set { ViewState[ "OriginalPagerPosition" ] = value; }
}
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack) OriginalPagerPosition = GridView1.PagerSettings.Position;
GridView1.PagerSettings.Position = PagerPosition.TopAndBottom;
GridView1.AllowPaging = true;
// databinding stuff ...
}
Keep the RowCreated the same as above in Pager approach.
Visibility of top/bottom pagers will be controlled in PreRender according to the OriginalPagerPosition property. Both pagers are created even with PagerPosition=TOP, the bottom pager is required for your additional control(s):
protected void Grid_PreRender(object sender, EventArgs e)
{
GridView gv = (GridView)sender;
GridViewRow tpr = (GridViewRow)gv.TopPagerRow;
GridViewRow bpr = (GridViewRow)gv.BottomPagerRow;
tpr.Visible = gv.PageCount > 1 && (OriginalPagerPosition == PagerPosition.Top || OriginalPagerPosition == PagerPosition.TopAndBottom);
bpr.Visible = true;
var tblBottomPager = (Table)bpr.Cells[ 0 ].Controls[ 0 ];
tblBottomPager.Rows[ 0 ].Visible = gv.PageCount > 1 && (OriginalPagerPosition == PagerPosition.Bottom || OriginalPagerPosition == PagerPosition.TopAndBottom);
var tblTopPager = (Table)tpr.Cells[ 0 ].Controls[ 0 ];
tblTopPager.Rows[1].Visible = false;
}
Note: if you are extending the GridView control, you have to replace all occurences of GridView1(my test-grid) with this.
It would be easy to add an extra row into the grid. But the difficulty in your requirement is that the GridView's RowCollection should not contain this row since that would be error-prone. It should also be the very last row even if paging is enabled. This is (afaik) not possible.
Hence i've chosen to extend the pager with this functionality.
I'll add this as separate answer since my other is already too detailed and describes two different ways(footer,pager) to add controls to a GridView without extending it.
This approach extends a GridView as in your own requirement and is similar to my other pager-approach. But it's cleaner and only adds the additional row to the BottomPager. It woks also for every setting(AllowPaging=false,Pager-Position: Top,Bottom,BottomTop):
[DefaultProperty("EnableUpdateAll")]
[ToolboxData("<{0}:UpdateGridView runat=server></{0}:UpdateGridView>")]
public class UpdateGridView : GridView
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("true")]
[Localizable(true)]
public bool EnableUpdateAll
{
get
{
Object val = ViewState["EnableUpdateAll"];
return ((val == null) ? true : (bool)val);
}
set
{
ViewState["EnableUpdateAll"] = value;
}
}
private bool OriginalAllowPaging
{
get
{
Object val = ViewState["OriginalAllowPaging"];
return (bool)val;
}
set
{
ViewState["OriginalAllowPaging"] = value;
}
}
private PagerPosition OriginalPagerPosition
{
get
{
Object val = ViewState["OriginalPagerPosition"];
return (PagerPosition)val;
}
set
{
ViewState["OriginalPagerPosition"] = value;
}
}
protected override void OnInit(System.EventArgs e)
{
if (ViewState["OriginalPagerPosition"] == null)
OriginalPagerPosition = base.PagerSettings.Position;
if(OriginalPagerPosition != PagerPosition.Bottom)
PagerSettings.Position=PagerPosition.TopAndBottom;
if (ViewState["OriginalAllowPaging"] == null)
OriginalAllowPaging = base.AllowPaging;
base.AllowPaging = true;
}
protected override void OnRowCreated(GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
case DataControlRowType.Pager:
//check if we are in BottomPager
if (this.Rows.Count != 0 && this.EnableUpdateAll)
{
Button btnUpdate = new Button();
btnUpdate.ID = "BtnUpdate";
btnUpdate.Text = "Update";
btnUpdate.Click += new EventHandler(UpdateAll);
var tblPager = (Table)e.Row.Cells[0].Controls[0];
var row = new TableRow();
var cell = new TableCell();
cell.ColumnSpan = tblPager.Rows[0].Cells.Count;
cell.Controls.Add(btnUpdate);
row.Cells.Add(cell);
tblPager.Rows.Add(row);
}
break;
}
}
protected override void OnPreRender(EventArgs e)
{
bool bottomPagerVisible =
OriginalAllowPaging &&
PageCount > 1 &&
(OriginalPagerPosition == PagerPosition.Bottom || OriginalPagerPosition == PagerPosition.TopAndBottom);
BottomPagerRow.Visible = bottomPagerVisible || EnableUpdateAll;
var tblBottomPager = (Table)BottomPagerRow.Cells[0].Controls[0];
tblBottomPager.Rows[0].Visible = bottomPagerVisible;
}
private void UpdateAll(Object sender, EventArgs e)
{
// do something...
}
}

How to add a row in asp.net grid view

So far I have done this, I am not sure whether this is right or wrong
public partial class _Default : System.Web.UI.Page
{
Label l = new Label();
GridView gv = new GridView();
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
GridViewRow gvr = new GridViewRow(i, i, DataControlRowType.DataRow, DataControlRowState.Normal);
gvr.Controls.Add(l);
gv. (what to do here)
}
this.Controls.Add(gv);
}
}
please help
gv.Rows.Add(gvr);
If you're starting with an empty GridView, an easier way to dynamically create x rows is to create a dummy list and then set it to the data source:
var list = new List<string>(10); // replace 10 with number of empty rows you want
// for loop to add X items to the list
gv.DataSource = list;
gv.DataBind();
If you are doing this, I'd recommend doing it with a Repeater. It's a lot easier to manage.
The DataGrid fires the RowCreate event when a new row is created.
Collapse
//OnRowCreated="GridView3_RowCreated"
protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
{
//When a child checkbox is unchecked then the header checkbox will also be unchecked.
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState ==
DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkselect");
CheckBox chkBxHeader = (CheckBox)this.GridView3.HeaderRow.FindControl("chkHeader");
chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(
this,'{0}');", chkBxHeader.ClientID);
}
}

Resources