i'm a newby at .NET and I'm having a problem with my checkboxes. They all return false, even if they are selected. Here is my asp code
<asp:GridView ID="gvGeneros1" runat="server" class="divTable"
AutoGenerateColumns="False" DataKeyNames="idgenero" CssClass="table">
<Columns>
<asp:BoundField DataField="nome" HeaderText="GĂȘnero" SortExpression="nome" >
<ControlStyle Width="200px" />
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:TemplateField AccessibleHeaderText="Check">
<ItemTemplate>
<asp:CheckBox ID="checkGenero" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here's my c# code
DataSet dsDivided;
protected void Page_Load(object sender, EventArgs e)
{
Music musicbll = new Music();
DataSet dsGeneros = musicbll.getGenders();
int size = dsGeneros.Tables[0].Rows.Count;
dsDivided = null;
// Divide in two DataTable
dsDivided = Tools.SplitDataTableInTwo((DataTable)dsGeneros.Tables[0], size / 2);
gvGeneros1.DataSource = dsDivided.Tables["FirstSet"];
gvGeneros1.DataBind();
for (int i = 0; i < gvGeneros1.Rows.Count; i++)
{
((CheckBox)gvGeneros1.Rows[i].Cells[1].Controls[1]).Checked=false;
}
}
protected void btGravarPrefs_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable("generos");
dt.Columns.Add("idgenero", typeof(int));
dt.Columns.Add("active", typeof(bool));
for (int i = 0; i < gvGeneros1.Rows.Count; i++)
{
int idCliente = (int)dsDivided.Tables[0].Rows[i][0];
bool check = ((CheckBox)gvGeneros1.Rows[i].Cells[1].Controls[1]).Checked; //always false
dt.Rows.Add(new object[] { idCliente, check});
}
}
}
I don't know what to try more, and i search all over and it seems right. Thanks
I think you should wrap your Data binding with if (!Page.IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Bind your datasource here
}
}
Related
I have a gridview as shown below and i want to hide a column named FREQ_BAND
,second column in button click named btnPmtCalculation which is out side gridview .How to do this ? i reached till this code but not able to proceed
<asp:gridview id="gvSpectrum" runat="server" headerstyle-cssclass="HomeGridHeader"
allowpaging="True" rowstyle-wrap="false" autogeneratecolumns="False" cssclass="table table-striped table-bordered"
cellpadding="4" datakeynames="FEES_CALC_FORMULA,BAND_ID,BAND,FREQ_BAND,SPECTRUM_ID" horizontalalign="Left" showfooter="true"
pagesize="10" onpageindexchanging="gvSpectrum_PageIndexChanging" onrowcommand="gvSpectrum_RowCommand">
<Columns>
<asp:BoundField DataField = "sl_num" HeaderText="SN" />
<asp:BoundField DataField = "FREQ_BAND" HeaderText="Frequency Band" />
<asp:BoundField DataField = "BW" HeaderText="Bandwidth / Quantity" />
<asp:BoundField DataField = "RANGE" HeaderText="Range" />
</Columns>
</asp:gridview>
<asp:button id="btnPmtCalculation" runat="server" text="Generate Permenant Sepctrum Invoice" onclick="btnPmtCalculation_Click">
Code I did as shown below
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
bool pemenant = true;
int spectrum_id = 0;
//Button btn = (Button)sender;
////Get the row that contains this button
//GridViewRow gvr = (GridViewRow)btn.NamingContainer;
foreach (GridViewRow row in gvSpectrum.Rows)
{
if (row.RowType == DataControlRowType.Header)
{
row.Cells[1].Visible = true;
}
}}
You can try this:
OnRowCreated
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columnIndex].Visible = false;
}
If you don't prefer the hard-coded index, the only workaround I can suggest is to provide a HeaderText for the GridViewColumn and then find the column using that HeaderText.
protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
((DataControlField)UsersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Email")
.SingleOrDefault()).Visible = false;
}
OnButtonClick
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
gvSpectrum.Columns[Index].Visible = false;
}
Simple, just hide the column in the button click.
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
gvSpectrum.Columns[i].Visible = false;
}
you can change your code with this:
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
bool pemenant = true;
int spectrum_id = 0;
int columnIndex = 1;
gvSpectrum.Columns[columnIndex].Visible = false;
}
'columnIndex' The column number is for hide it
or if you want hide with column Header Text Use this code:
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
foreach(DataControlField col in gvSpectrum.Columns)
{
if (col.HeaderText == "Email")
col.Visible = false;
}
}
Try this:
protected void btnPmtCalculation_Click(object sender, EventArgs e)
{
gvSpectrum.Columns[columnindex].Visible = false;
//OR
gvSpectrum.Columns["columnname"].Visible = false;
}
I have below code to create a gridview in asp.net and inside gridview I have a delete button. Below code works fine and shows Delete in all rows.
I want to hide/ Disable the Delete button in very first row. Can somebody suggest the code part?
<asp:gridview ID="Gridview1" runat="server"
ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Cat">
<ItemTemplate>
<asp:TextBox ID="TextBoxCat" runat="server" Enabled="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" >
<ItemTemplate>
<asp:LinkButton ID="DeleteItemsGridRowButton" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
You can use GridView.RowDataBound Event event.
Then find the LinkButton using FindControl method.
public class Animal
{
public int RowNumber { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Gridview1.DataSource = new List<Animal>
{
new Animal {RowNumber = 1, Name = "One"},
new Animal {RowNumber = 2, Name = "Two"},
new Animal {RowNumber = 3, Name = "Three"},
new Animal {RowNumber = 4, Name = "Four"},
};
Gridview1.DataBind();
}
}
private int _counter;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (_counter == 0)
{
var linkButton = e.Row.FindControl("DeleteItemsGridRowButton")
as LinkButton;
linkButton.Visible = false;
_counter++;
}
}
}
Try This:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(GridView1.Rows.Count>0)
{
//GridView1.Rows[0].Visible = false;
LinkButton DeleteItemsGridRowButton= (LinkButton) GridView1.Rows[0].FindControl("DeleteItemsGridRowButton");
if(DeleteItemsGridRowButton!=null)
{
DeleteItemsGridRowButton.Visible=false
}
}
}
Please help me with following, just something weird is going on.
I have a gridview with paging where the first column is filled with checkboxes.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="..." DataKeyNames="EventID" EnableViewState="false"
GridLines="None" AllowSorting="True"
AllowPaging="True" Width="100%"
onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender">
<HeaderStyle Wrap="false" />
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<HeaderTemplate>
<asp:CheckBox ID="SelectAllEvs" runat="server" EnableViewState="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="EventSelector" runat="server" EnableViewState="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ... >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
</Columns>
</asp:GridView>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["PageIndex"] != null)
{
GridView1.PageIndex = Convert.ToInt32(Session["PageIndex"]);
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
// loading checkbox values from the session collection
GridView gv = (GridView)sender;
LoadCheckboxState(gv);
Session["PageIndex"] = gv.PageIndex;
}
private void LoadCheckboxState(GridView gv)
{
for (int i = 0; i < gv.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (SelectedIndexes.Contains(id))
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
private List<int> SelectedIndexes
{
get
{
if(Session["selectedRows"] == null)
{
Session["selectedRows"] = new List<int>();
}
return (List<int>)Session["selectedRows"];
}
}
private void SaveCheckboxState(GridView gv)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (chkBox.Checked)
{
//see if we have an id added already
if (!SelectedIndexes.Contains(id))
{
SelectedIndexes.Add(id);
}
}
else
{
if (SelectedIndexes.Contains(id))
{
SelectedIndexes.Remove(id);
}
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// saving current page checkbox values to the session collection
GridView gv = (GridView)sender;
SaveCheckboxState(gv);
GridView1.PageIndex = e.NewPageIndex;
}
When I first get to my page I check some checkboxes and then press F5. Apparently after pressing it I dont have any values in SelectediIndexes and all unselected checkboxes must be checked = false on the PreRender stage but they appear checked after all this. And the problem of the same nature: I checked some on the first page; went to the second page (currently having 2 indexes in the SelectedValues) and after pressing F5 the same I have checked the same checkboxes as on the first page, though they mustn't. I'm absolutely confused with this. How can I fix this? Thanx for any help.
I've found the reason to that strange behavior. I'm using Firrefox. And one of the features of this browser is saving state of some fields when refreshing the page. If you want to refresh a page fully you should refresh it with pressed shift button. Tested in Google Chrome - works just fine.
Hi I want to have a DropDownList outside of my GridView that displays a list of page numbers. When the user clicks on a page number, the GridView should go to that page. I am able to populate the DropDownList, but it's not working with the GridView
Here is my GridView and DropDownList
<asp:DropDownList ID="ddlPageNumber" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlPaging_SelectedIndexChanged">
</asp:DropDownList> of
<%=GridView1.PageCount%>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" BorderStyle="Solid" GridLines="Both" HeaderStyle-BackColor="#990033" Width="1000px"
DataSourceID="EntityDataSource1" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound">
<HeaderStyle ForeColor="White"></HeaderStyle>
<Columns>
<asp:BoundField DataField="intBatchID" HeaderText="Batch ID" ReadOnly="True"
SortExpression="intBatchID" />
<asp:BoundField DataField="vcharName" HeaderText="Name" ReadOnly="True"
SortExpression="vcharName" />
<asp:BoundField DataField="dtmScheduled" HeaderText="Date Scheduled"
ReadOnly="True" SortExpression="dtmScheduled" />
<asp:BoundField DataField="intBatchPriorityLevel"
HeaderText="Priority Level" ReadOnly="True"
SortExpression="intBatchPriorityLevel" />
</Columns>
<PagerSettings Mode="NumericFirstLast" Position="TopAndBottom" PageButtonCount="4" PreviousPageText="Previous" NextPageText="Next" FirstPageText="First" LastPageText="Last" />
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
Here's my code behind
protected void GridView1_DataBound(object sender, EventArgs e)
{
for (int cnt = 0; cnt < GridView1.PageCount; cnt++)
{
int curr = cnt + 1;
ListItem item = new ListItem(curr.ToString());
if (cnt == GridView1.PageIndex)
{
item.Selected = true;
}
ddlPageNumber.Items.Add(item);
}
}
protected void ddlPaging_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.PageIndex = ddlPageNumber.SelectedIndex;
}
After you update the PageIndex you need to rebind the grid, like this:
protected void ddlPaging_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.PageIndex = ddlPageNumber.SelectedIndex;
GridView1.DataBind();
}
UPDATE:
Since you are dynamically building the drop down list items for the page numbers, then you need to re-build them whenever a post back to the server happens or whenever the grid is rebound, like this:
private void BuildPageNumbers()
{
ddlPageNumber.Items.Clear();
for (int cnt = 0; cnt < GridView1.PageCount; cnt++)
{
int curr = cnt + 1;
ListItem item = new ListItem(curr.ToString());
if (cnt == GridView1.PageIndex)
{
item.Selected = true;
}
ddlPageNumber.Items.Add(item);
}
}
Now in your DataBound and Page_Load events, you can call this method, like this:
protected void Page_Load(object sender, EventArgs e)
{
BuildPageNumbers();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
BuildPageNumbers();
}
I have this manually update code for my radgrid (RAD13).
on upload it works but the thing is that only the first row in the grid saves it's update.
I think that I should passe a value that will autoincrement to passe through rows
protected void UpdateButton_Click(object sender, EventArgs e)
{
RadGrid grid = (this.FindControl("RAD13") as RadGrid);
(grid.MasterTableView.GetItems(GridItemType.EditItem)[0] as GridEditableItem).FireCommandEvent(RadGrid.UpdateCommandName, string.Empty);
}
Please try with the below code snippet.
ASPX
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
OnUpdateCommand="RadGrid1_UpdateCommand" AllowFilteringByColumn="true" AllowPaging="true"
AllowMultiRowEdit="true">
<MasterTableView DataKeyNames="ID" EditMode="InPlace">
<Columns>
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
</telerik:GridBoundColumn>
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="update All edit row" />
ASPX.CS
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
dynamic data = new[] {
new { ID = 1, Name = "Name1"},
new { ID = 2, Name = "Name2"},
new { ID = 3, Name = "Name3"},
new { ID = 4, Name = "Name4"},
new { ID = 5, Name = "Name5"}
};
RadGrid1.DataSource = data;
}
protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem item = e.Item as GridEditableItem;
UpdateLogic(item);
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridEditableItem item in RadGrid1.EditItems)
{
UpdateLogic(item);
item.Edit = false;
}
RadGrid1.Rebind();
}
protected void UpdateLogic(GridEditableItem item)
{
// perform your update logic here
}
Let me know if any concern.