I'm using a dropdownlist inside a detailsview and it populates well, but when I do a insert there is a postback so I'm trying to bind the DDL again but the values are lost somehow.
My aspx:
<asp:UpdatePanel ID="InsertPanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableHeaderRow SkinID="tableheaderrowSkin">
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell BackColor="DarkGray" BorderColor="DarkGray" BorderWidth="1" Width="300">
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="nFuturesId"
DataSourceID="FutureCommodityODS" DefaultMode="Insert" OnItemInserting="DetailsView1_ItemInserting"
SkinID="detailsviewSkin" OnItemInserted="DetailsView1_ItemInserted" EnableModelValidation="True">
<BrummerComp:SortableDropDownList ID="DropDownListFuturesInsert" runat="server" SkinID="BCdropdownlistSkin">
</BrummerComp:SortableDropDownList>
</asp:DetailsView>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
I populate the DDL in Page_Load:
protected new void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindDropDownList();
}
//DetailsView1.DataBind();
}
BindDropDownList:
private void BindDropDownList()
{
var paperFutureList = (List<PaperFutures>)DataManager.GetPaperFutures();
var ddl = (DropDownList)DetailsView1.FindControl("DropDownListFuturesInsert");
ddl.DataSource = paperFutureList;
ddl.DataValueField = "nFuturesID";
ddl.DataTextField = "ShortNameAndFutureNameAndFutureId";
ddl.DataBind();
}
The problem is when I do a insert in my detailsview the DDL is loses it's values. I have tried databind the detailsview but then the values won't load at all.
The method BindDropDownList works well in Page_Load the first time. Also tried putting the methodcall outside !IsPostBack to always populate it but that doesn't work either.
I have checked GetPaperFutures() and it works well every time, so the problem is somewhere else, but I can't find where.
I was facing the similar problem. Eventually, I have found the solution!
Just call the BindDropDownList() in Page_PreRender event.
It works successfully!
Related
I have a gridview on a .NET forms application, and on postback, I am not seeing the values entered in the textbox within a gridview.
ASPX:
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="false" ShowHeader="false" DataKeyNames="ItemId" EnableViewState="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtItem" runat="server" Text="0" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemId" />
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btn" Text="Submit" OnClick="btn_OnClick" OnClientClick="javascript:return someClientStuff();" />
Code Behind:
protected void btn_OnClick(object sender, System.EventArgs e)
{
foreach(GridViewRow row in gvItems.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var itemId = Convert.ToInt32(gvItems.DataKeys[row.RowIndex].Values[0]);
var itemValue = ((row.Cells[0].FindControl("txtItem") as TextBox).Text;
}
}
I am seeing itemId populated for each row, but itemValue is always empty string.
Been a while since I worked on a forms application, any help is appreciated!
I will assume that the DataBind of the GridView is not in if(!IsPostBack). Add this to the Page_Load
if(!IsPostBack)
{
gvItems.DataSource = soruceOftheGrid
gvItems.DataBind();
}
On the button click, try to store the values in the view state and within page load event, try to assign the viewstate back to the grid view as for each postback, page load event is called. Its good to assign the values back to grid view within page load, this will help you to retain the values you have entered.
I'm trying to load/reload a GridView based on the OnSelectedIndexChanged event of a DropDownList. The ddl has AutoPostBack set to true, but still the Grid won't load, unless I encapsulate it within an UpdatePanel. But once I do that, my FileUpload control stops working... What would be the best solution for this problem?
**Edit ** Relevant code:
aspx file
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="upProva" runat="server">
<ContentTemplate>
<%--user control for data selection--%>
<asp:DropDownList ID="ddlAula" runat="server" DataTextField="nmAula" DataValueField="idAula"
CssClass="medio" Enabled="false" AutoPostBack="true" OnSelectedIndexChanged="ddlAula_OnSelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="gvQuestoes" runat="server" AutoGenerateColumns="False" CssClass="gv"
AllowSorting="false" DataKeyNames="idQuestao" OnRowCommand="gvQuestao_RowCommand">
<Columns>
<%--(...)--%>
</Columns>
</asp:GridView>
<asp:Button ID="btnSalvar" runat="server" ToolTip="Salvar" CssClass="botao40 salv40"
OnClick="btnSalvar_Click" ValidationGroup="trabalho" />
<asp:FileUpload ID="fuAnexo" runat="server" CssClass="fileOriginal" />
</asp:Content>
codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnArquivo.OnClientClick = "document.getElementById('" + fuAnexo.ClientID + "').click(); return false;";
txtAnexo.Attributes.Add("onclick", "document.getElementById('" + fuAnexo.ClientID + "').click(); return false;");
fuAnexo.Attributes.Add("onchange", "document.getElementById('" + txtAnexo.ClientID + "').value = this.value;");
}
}
protected void ddlAula_OnSelectedIndexChanged(object sender, EventArgs e)
{
gvQuestoes.DataSource = Questao.CarregarPorAula(Int32.Parse(ddlAula.SelectedValue));
gvQuestoes.DataBind();
}
The DataSource/Databinding is correct (I know because I've added a button to the page, and used the same binding code on the Button _Click event and it works).
You need to rebind the gridview in OnSelectedIndexChanged event. Something like
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Do your processing logic
gridview1.DataSource = new_modified_datasource;
gridview1.DataBind();
}
I found a fairly simple (though not ideal in all cases) with PostBackTrigger:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="upProva" runat="server">
<ContentTemplate>
<%--user control for data selection--%>
<asp:DropDownList ID="ddlAula" runat="server" DataTextField="nmAula" DataValueField="idAula"
CssClass="medio" Enabled="false" AutoPostBack="true" OnSelectedIndexChanged="ddlAula_OnSelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="gvQuestoes" runat="server" AutoGenerateColumns="False" CssClass="gv"
AllowSorting="false" DataKeyNames="idQuestao" OnRowCommand="gvQuestao_RowCommand">
<Columns>
<%--(...)--%>
</Columns>
</asp:GridView>
<asp:FileUpload ID="fuAnexo" runat="server" CssClass="fileOriginal" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSalvar" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
Nowhere in your code do you show how you populate ddlAula. So here is my answer: the Page_Load you've shown is abbreviated, and actually you are populating ddlAula there. Furthermore, you are doing it each time, rather than checking IsPostBack. Therefore by the time your eventhandler for ddlAula is hit, the list has been reset and the value you selected is no longer selected.
If my answer is correct, you need to add the check in Page_Load:
if (!IsPostBack)
{
//populate ddlAula
}
I have a Gridview control and I have placed a RadioButton in the itemtemplate. When I click a button I'm trying to get the checked property of the radio button. But When I click the checked property is always returning false. Please look into the below code and let me know where I'm making mistake.
aspx Code
<asp:GridView ID="gvDepartments" runat="server" AutoGenerateColumns="False" GridLines="None"AllowPaging="true" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rdbtn" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lbl" runat="server"></asp:Label>
<asp:Button ID="btn" runat="server" Text="Save" OnClick="btn_Click" CssClass="button small"/>
Code Behind on button click
foreach (GridViewRow row in gvDepartments.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
RadioButton rd = (RadioButton)row.FindControl("rdbtn");
lbl.Text += rd.Checked.ToString();// +rd1.Checked.ToString();
}
}
Result will be False always in the label always. I'm using Ajaxcontroltoolkit in the application, Above controls are present in the update panel and I even tried to placing button and event in the triggers but the result is same. Please help.
Regards,
Nuthan A R
When do you assign and load the DataSource of the GridView? Note that you should do that only if(!IsPostBack) and not on every postback. So use the Page.IsPostBack property.
So assuming that you're using Page_Load for this:
protected void Page_Load(Object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataBindGridView(); // method that assigns DataSource and calls DataBind
}
}
How to access gridview cells of a particular selected and checked row. Below are the codes
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True">
<Columns>
<asp:TemplateField HeaderText="IsApproved">
<ItemTemplate>
<asp:CheckBox ID="chkApproved" runat="server" CommandName="Approve" />
</ItemTemplate></asp:TemplateField></Columns></asp:GridView>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Text="Approve" Value="1"></asp:ListItem>
<asp:ListItem Text="Reject" Value="2"></asp:ListItem>
</asp:RadioButtonList>
The datasource of gridview is set by strongly typed data sets on Page_Load. Now on btnSubmit I want to insert the selected row into my database table if it is checked
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedValue == "1")
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("chkApproved") as CheckBox;
if (chk.Checked)
{
DataSet1TableAdapters.tbl_ApproveTableAdapter ta = new DataSet1TableAdapters.tbl_ApproveTableAdapter();
DataSet1.tbl_ApproveDataTable dt = new DataSet1.tbl_ApproveDataTable();
ta.Insert()// here I've to specify the cells of GV
}
}
}
}
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
I've two issues here
i) To access the gridview cells if the row is checked in the checkbox
ii) On my GV select it is automatically set to AutoPostback which I want to disable as it is clearing the selected checkboxes.
.
Update panel automatically post back but you can disable autopostback by using AsyncPostBackTrigger. Set the ChildrenAsTriggers property to true and the UpdateMode property to Conditional
<asp:UpdatePanel ID="myPanel" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
// put your code here to avoid autopost back
</ContentTemplate>
</asp:UpdatePanel>
Another way to disable autopostback is to set AutoPostBack to false...
<asp:RadioButtonList ID="RadioButtonList1" AutoPostBack="False">
You need to bind gridview like this
if (!Page.IsPostBack)
{
GridView1.DataSource = source;
GridView1.DataBind();
}
and try. Sure it will give your expected result.
Try to use CommandArgument='<%# Container.DataItemIndex %>' attribute in the .
It return index of selected GridView row.
Then on click event you can write logic to fetch value of specific rows and columns of selected gridview row.
For example if you want to access 3rd column of 1st row you can write
GridView.Rows[0].Cells[2].Text in click event or checkedchange event to fetch value.
I have a LinkButton inside a GridView that passes a CommandArgument and tries to fire RowCommand
GridView declaration:
<asp:GridView PageIndex="0" OnRowCommand="GridView1_RowCommand" PageSize="10" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging"
ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" Width="700px"
AutoGenerateColumns="False" OnPageIndexChanged="GridView1_PageIndexChanged">
LinkButton inside the GridView:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClientClick="return confirm('Are you sure you want to delete this checklist?');" runat="server" CausesValidation="false" CommandName="DeleteChecklist" CommandArgument='<%# Eval("refID") %>' Text="Delete"></asp:LinkButton>
</ItemTemplate>
<ItemStyle ForeColor="Black" />
<ControlStyle BorderStyle="None" ForeColor="Black" />
</asp:TemplateField>
Code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteChecklist")
{
string refID = e.CommandArgument.ToString();
DAL.DeleteChecklist(refID);
}
}
I placed a breakpoint at RowCommand but it doesn't get fired at all, any idea why?
I assume that you're databinding the GridView on postbacks. So always embed it in a if(!IsPostBack) check:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
GridView1.DataSource = getSource();
GridView1.DataBind();
}
}
Otherwise events won't be triggered and edited values will be overridden.
Another possible reason: Have you disabled ViewState?
EDIT2: Ok it got better. You can make it work with AllowCustomPaging="true" but the property VirtualItemCount must have to be greater than the PageSize value of your grid view. Look at this:
<asp:GridView runat="server" ID="gvPresupuestos" AutoGenerateColumns="False"
OnRowCommand="gvPresupuestos_RowCommand"
OnPageIndexChanging="gvPresupuestos_PageIndexChanging"
OnPreRender="gvPresupuestos_PreRender" ItemType="Core.NominaEntities.TipoPresupuesto"
AllowPaging="true" PageSize="1" AllowCustomPaging="true"
UseAccessibleHeader="true" GridLines="None" CssClass="table table-hover"
ShowHeaderWhenEmpty="True">
<Columns>
<asp:BoundField HeaderText="Nombre del presupuesto" DataField="Nombre" />
<asp:TemplateField HeaderText="Opciones">
<ItemTemplate>
<a href='<%# "Detalle?p=" + Item.IdTipoPresupuesto.ToString() %>'
target="_self"><%# Item.Editable ? "Editar" : "Ver" %></a>
<asp:LinkButton runat="server"
CommandArgument='<%# Item.IdTipoPresupuesto.ToString() %>'
CommandName="Deshabilitar"
Text="Deshabilitar" Visible='<%# !Item.Editable ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
FillView() method:
private void FillView(int desiredPage)
{
var cliente = ClientFactory.CreateAuthServiceClient();
using (cliente as IDisposable)
{
// this list only has 1 item.
List<TipoPresupuesto> resultado = cliente.ObtenerTiposDePresupuesto();
gvPresupuestos.DataSource = resultado;
// For testing pursposes, force the virtual item count to 1000.
gvPresupuestos.VirtualItemCount = 1000;
gvPresupuestos.DataBind();
}
}
So, the LinkButton does not fire the gvPresupuestos_RowCommand event unless the virtual item count is greater than the VirtualItemCount property.
I hope this helps.
EDIT1: I found it. You can make it work by changing the value of "AllowCustomPaging" to false. I don't know why, but hope this can help.
ORIGINAL 'ANSWER':
I have the same problem. You can see the my code here:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div class="jumbotron jumbotron-small">
<h2>Presupuestos</h2>
</div>
<asp:GridView runat="server" ID="gvPresupuestos"
AutoGenerateColumns="False" AllowPaging="true" AllowCustomPaging="true" PageSize="20"
OnRowCommand="gvPresupuestos_RowCommand"
OnPageIndexChanging="gvPresupuestos_PageIndexChanging"
DataKeyNames="IdTipoPresupuesto" OnPreRender="gvPresupuestos_PreRender"
ItemType="Core.NominaEntities.TipoPresupuesto" ShowHeaderWhenEmpty="True"
UseAccessibleHeader="true" GridLines="None" CssClass="table table-hover">
<Columns>
<asp:BoundField HeaderText="Nombre del presupuesto" DataField="Nombre"/>
<asp:TemplateField HeaderText="Opciones">
<ItemTemplate>
<asp:LinkButton runat="server" Text="Deshabilitar"
Font-Underline="true" CommandName="Deshabilitar"
Visible='<%# Item.Editable ? true : false %>'
CommandArgument='<%# Item.IdTipoPresupuesto %>' />
<a href='<%# "Detalle?p=" + Item.IdTipoPresupuesto.ToString() %>'
target="_self"><%# Item.Editable ? "Editar" : "Ver" %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Link" CommandName="Deshabilitar"
Text="Deshabilitar (this fires event)" />
</Columns>
</asp:GridView>
<table class="large-table">
<tr>
<td class="text-right">
<a runat="server" class="btn btn-primary" href="Detalle">Nuevo presupuesto</a>
</td>
</tr>
</table>
</asp:Content>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitializeControls();
SetPermissions();
FillView(1);
}
}
protected void gvPresupuestos_PreRender(object sender, EventArgs e)
{
// Habilita bootstrap
gvPresupuestos.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void gvPresupuestos_RowCommand(object sender, GridViewCommandEventArgs e)
{
// This is never fired by the LinkButton in the ItemTemplate
// But the ButtonField actually fires it.
if (e.CommandName.Equals("Deshabilitar"))
{
// This is how I've been doing it in the whole project but thanks to this
// shit I can't use the CommandArgument of the LinkButton in the ItemTemplate
// Guid idPresupuesto = new Guid(e.CommandArgument.ToString());
// I don't know what I'm supposed to do now.
// ¿Why this only happens in this page?, ¿WTF?
Guid idPresupuesto = gvPresupuestos.GetTheIdFromDataKeysWithFuckingMagic();
var cliente = ClientFactory.CreateServiceClient();
using (cliente as IDisposable)
{
cliente.DeshabilitarPresupuesto(idPresupuesto);
}
}
FillView(1);
}
protected void gvPresupuestos_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvPresupuestos.PageIndex = e.NewPageIndex;
FillView(e.NewPageIndex + 1);
}
#region helper methods
private void InitializeControls()
{
// Not required yet
}
private void FillView(int desiredPage)
{
var cliente = ClientFactory.CreateAuthServiceClient();
using (cliente as IDisposable)
{
var resultado = cliente.ObtenerTiposDePresupuesto();
gvPresupuestos.DataSource = resultado;
gvPresupuestos.DataBind();
}
}
private void SetPermissions()
{
// not required yet
}
#endregion
I've tried enabling and disabling viewstate in the gridview but didn't get different results.
Here is what happens with breakpoints:
You type the url and load the page for the first time.
Then you access the code in the block if(!IsPostBack).
Now you can click both the LinkButton in the ItemTemplate and the ButtonField(Look screenshot)
If you click the LinkButton in the ItemTemplate, it doesn't fire gvPresupuestos_RowCommand. It does a postback, of course. But gvPresupuestos_RowCommand simply doesn't get fired. My code doens't handle that weird postback and the page does the things it would do with a regular postback. After it, you end up with an empty gridview because in the flow of this postback, FillView() is never called.(Look screenshot)
If you click the ButtonField, the event gvPresupuestos_RowCommand is fired, and everything is normal. But I require the IdPresupuesto of the clicked row and I don't know how to get it now.
This is weird. I've implemented this model in all the info pages of the system (there are like 15 modules like this) and never had problems until now.
I had the same problem for a LinkButton in a ListView.
Turns out I should have been using OnItemCommand in the ListView, not OnRowCommand.
Changing this fixed the issue.
Also, you must have a CommandName set on the LinkButton (but no OnCommand).