I want to insert specific row values based on check box click. The design and source is given below. From the design I have to select some Items. If I click approve, I have to store those check box checked row values into DB. Help me to find a proper solution.
Design:
ASPX:
C#:
The given below code is getting the entire gridview value and storing into db. How can I modify this code as per above requirements.
protected void btnApprove_Click(object sender, EventArgs e)
{
ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter rs;
rs = new ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter();
foreach (GridViewRow row in GridView2.Rows)
{
string ItemName = row.Cells[0].Text;
string Quantity = row.Cells[1].Text;
rs.testInsert(ItemName, Quantity);
}
}
You need to iterate through your gridview and find check box by Id in cell of current row.
foreach (GridViewRow row in GridView2.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
bool chk = chkRow.Checked;
// Do your stuff
}
}
Source: http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx
The given below code is working perfectly.
foreach (GridViewRow row in GridView2.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
string ItemName = row.Cells[0].Text;
string Quantity = row.Cells[1].Text;
rs.testInsert(ItemName, Quantity);
}
}
}
Here is my GridView
<asp:GridView
ID="grdAccounts"
class="table table-condensed"
runat="server"
AutoGenerateColumns="False"
CellPadding="4"
ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="CUST_NAME" HeaderText="Name" />
<asp:BoundField DataField="CUST_NUMBER" HeaderText="Account Number" />
<asp:BoundField DataField="BR_CODE" HeaderText="CIF Number" />
<asp:TemplateField HeaderText="Select" >
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" ItemStyle-HorizontalAlign="Right" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="SingleCheckboxCheck(this)" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle CssClass="pagination-ys" />
<RowStyle BackColor="#E3EAEB" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
c#(I assumed as the required value is in the 1 cell of the selected row.)
string accnbr = string.Empty;
foreach (GridViewRow gvrow in grdAccounts.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("CheckBox1");
if (chk != null & chk.Checked)
{
cif += gvrow.Cells[1].Text + ',';
}
}
Related
I have a GridView that I populate from my SQL. The grid has a page size of 7. I'm making use of the RowDataBound event to replace "<" and ">" characters with "`" which works as expected.
However, the problem is that it disables Paging on the grid. When the grid has more than 7 items, paging should be enabled so that I can go to Page 2, but the paging doesn't work as soon as I use the RowDataBound event.
My code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserID"] != null)
{
GrdOpsBook.DataSource = OperationalEmployees.getEmpbookedBySpecificDate(DateTime.Today);
GrdOpsBook.DataBind();
if (GrdOpsBook.Rows.Count == 0)
lblNoOpsBooking.Visible = true;
lblWelcome.Text = "Welcome " + Session["UserLoggedInName"] + " to the Energy Insight Booking Application";
}
else
Response.Redirect("LogIn.aspx");
}
protected void GrdOpsBook_RowDataBound1(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
cell.Text = cell.Text.Replace(">", "`");
cell.Text = cell.Text.Replace("<", "`");
}
}
My GridView
<asp:GridView ID="GrdOpsBook" runat="server" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
CellPadding="4" AllowPaging="True" EnableSortingAndPagingCallbacks="True"
PageSize="7"
ForeColor="Black" GridLines="Vertical" Width="100%" AutoGenerateColumns="False" >
<AlternatingRowStyle BackColor="LightGray" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
<Columns>
<asp:BoundField DataField="Operator" HeaderText="Operator" ItemStyle-Width="10%" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Destination" HeaderText="Destination" ItemStyle-Width="58%" HtmlEncode="false" ItemStyle-Wrap="true"/>
<asp:BoundField DataField="Start Time" HeaderText="Start Time" ItemStyle-Width="6%" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:hh\:mm}" />
<asp:BoundField DataField="End Time" HeaderText="End Time" ItemStyle-Width="6%" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:hh\:mm}" />
<asp:BoundField DataField="Booked By" HeaderText="Booked By" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Number of Days Booked" HeaderText="Number of Days Booked" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
over here you iterate over each row
protected void GrdOpsBook_RowDataBound1(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
cell.Text = cell.Text.Replace(">", "");
cell.Text = cell.Text.Replace("<", "");
}
}
you should restrict your iteration to DataRows
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState != DataControlRowState.Edit)
Thank you, I did it this way and it works well without disabling the paging
protected void GrdOpsBook_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Replace the "<" tag with "`".
string sDestination = e.Row.Cells[1].Text.Replace("<", "`");
e.Row.Cells[1].Text = sDestination;
}
}
I have a gridview control on my web form with 1 template field column.
And i am adding some bounded columns at run time from code behind.
And some times I've removed some of the previously added columns from code behind.
After removing any column gridview losses template column.
What is the cause behind this and how can i prevent template column with out setting EnableViewState="false".
Edit-1
.aspx page Code
<asp:GridView ID="grvSum" runat="server" Width="100%" GridLines="None" AllowPaging="True" ShowFooter="true"
PageSize="25" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="false" AllowSorting="true" EnableViewState="false"
OnRowUpdating="grvSum_RowUpdating" OnPageIndexChanging="grvSum_PageIndexChanging" OnSorting="grvSum_Sorting"
OnRowDataBound="grvSum_RowDataBound" Font-Size="10px">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="dtype" runat="server" CommandName="update"
CssClass="lbl" Font-Underline="true" style="cursor:pointer;" Text="Details" >
</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px"/>
<FooterTemplate>
<asp:Label ID="lblFooter" runat="server" Text="Total"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" HorizontalAlign="Center"/>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Center"/>
<HeaderStyle HorizontalAlign="Center" BackColor="#507CD1" Font-Bold="True" ForeColor="White" Height="30px" Wrap="true"/>
<PagerStyle HorizontalAlign="Right" CssClass="GridPager" />
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Center"/>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" CssClass="headerSortUp" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" CssClass="headerSortDown"/>
</asp:GridView>
Code for adding and removal of column
public void AddBoundedColumns(GridView grv, DataColumnCollection dtDataSourceColumns)
{
var gridBoundColumns = grv.Columns.OfType<BoundField>();
foreach (DataColumn col in dtDataSourceColumns)
{
//Check existence of column in gridview
if (gridBoundColumns.Any(bf => bf.DataField.Equals(col.ColumnName)) == false)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
bfield.SortExpression = col.ColumnName;
//Add the newly created bound field to the GridView.
grv.Columns.Add(bfield);
}
}
gridBoundColumns = grv.Columns.OfType<BoundField>();
int z = 0;
for (int x = 0; x < gridBoundColumns.Count(); x++)
{
BoundField c = gridBoundColumns.ElementAt(z);
if (!dtDataSourceColumns.Contains(c.HeaderText))
{
grv.Columns.Remove(c);
}
else
{
z++;
}
}
}
instead of grv.Columns.Remove(c);, try following while removing the column
grv.columns.RemoveAt(index); //"index" is the index of column you want to remove
I have a gridview with a linkbutton, the url linkbutton is assigned using a code by replacing a key word with a name from the DB.
all works fine, except that when I click the back button in browser and try different link I get this error:
"The HTTP verb POST used to access path '/System.Web.UI.WebControls.Label' is not allowed"
below is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var HyperLink = row.FindControl("LinkButton1") as LinkButton;
var RepID = row.FindControl("Label1") as Label;
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", RepID.Text + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="report_id" DataSourceID="SqlDataSource1" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("report_name")%>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("report_subject")%>'></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="center"
VerticalAlign="Middle" />
<ItemStyle CssClass="link3" HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
I think the problem might be that you're doing your binding at the Page_Load stage of the page life cycle. Try moving your foreach code to a
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var HyperLink = e.Row.FindControl("LinkButton1") as LinkButton;
//var RepID = row.FindControl("Label1") as Label;
//You should be able to access your field without referencing the label too
DataRow row = ((DataRowView)e.Row.DataItem).Row;
var myField = row.Field<string>("report_name");
if (RepID != null)
{
StringBuilder lnk = new StringBuilder("http://bhvwtwbis2/Ops/_layouts/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/Ops/GAPPBASE/Reports/kai.rdl&Source=http%3A%2F%2Fbhvwtwbis2%2FOps%2FGAPPBASE%2FForms%2FAllItems%2Easpx%3FRootFolder%3D%252FOps%252FGAPPBASE%252FReports%26FolderCTID%3D0x012000D833091DB062524DA7A0550847E4E075%26View%3D%7B8A039A42%2D111E%2D40C4%2D8489%2D0D7F32CEAF36%7D&DefaultItemOpen=1");
lnk.Replace("kai", myField + "x1");
HyperLink.PostBackUrl = lnk.ToString();
}
}
}
i am doing to this with my gridview in aspx file
<asp:GridView ID="gridDepartement" runat="server" CellPadding="4" ForeColor="Black"
GridLines="Horizontal" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" AllowSorting="True" >
<Columns>
<asp:templatefield>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll"
runat="server" AutoPostBack="true"
OnCheckedChanged="cbSelectAll_CheckedChanged" />
</HeaderTemplate>
<itemtemplate>
<asp:CheckBox Id="cbSelectOne" runat="server"/>
</itemtemplate>
</asp:templatefield>
<asp:CommandField ShowEditButton="True" ItemStyle-Width="20"/>
<asp:CommandField ShowDeleteButton="True" ItemStyle-Width="20"/>
<asp:CommandField ShowSelectButton="True" ItemStyle-Width="20"/>
<asp:boundfield headertext="Departement Code" datafield="departementcode"
ItemStyle-HorizontalAlign="Center"/>
<asp:boundfield headertext="Departement Name" datafield="departementname"
ItemStyle-HorizontalAlign="Center" />
<asp:boundfield headertext="Created By" datafield="createby"
ItemStyle-HorizontalAlign="Center" />
<asp:boundfield headertext="Created Date" datafield="createdate"
ItemStyle-HorizontalAlign="Center" />
<asp:boundfield headertext="Updated By Name" datafield="updateby"
ItemStyle-HorizontalAlign="Center" />
<asp:boundfield headertext="Last Update" datafield="lastupdate"
ItemStyle-HorizontalAlign="Center" />
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
and i want check all checkbox when checkbox header clicked, so i add an event to my grid, and add this code in checkbox checkchanged event :
protected void cbSelectAll_CheckedChanged(object sender, EventArgs e)
{
bool chkFlag = false;
CheckBox cbHD = (CheckBox)gridDepartement.HeaderRow.FindControl("cbSelectAll");
if (cbHD.Checked)
{
chkFlag = true;
}
foreach (GridViewRow dr in gridDepartement.Rows)
{
CheckBox chk = (CheckBox)dr.Cells[0].FindControl("cbSelectOne");
chk.Checked = chkFlag;
}
}
page load code :
protected void Page_Load(object sender, EventArgs e)
{
//if(!IsPostBack)
//{
DataSourceDepartement dpt = new DataSourceDepartement();
DataSourceDepartementTableAdapters.departementTableAdapter
adp = new DataSourceDepartementTableAdapters.departementTableAdapter();
//bind gridview to datatable
gridDepartement.DataSource = adp.GetDataDepartement();
gridDepartement.DataBind();
//}
}
ok it's working now, but now the problem is, my checkbox event only trigered when it is value turn to checked /true, but when i uncheck it / turn it to false, it does not trigered, what part i should fix?
Why to do this thing in server side. Do it in java script. That will be better for performance level.Use this code::: `function CheckAll(objparentcheckbox) {
var HeaderCheckboxControl = objparentcheckbox
var table = getParentByTagName(HeaderCheckboxControl, 'table');
//get all the control of the type INPUT in the base control.
var Inputs = table.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox') {
Inputs[n].checked = HeaderCheckboxControl.checked;
}
return false;
} and in grid:::: <HeaderTemplate>
<asp:CheckBox ID="ChkSelectAll" onclick="CheckAll(this)" runat="server" />
</HeaderTemplate>`
Your Gridview is binded again before the event of checkbox, thats why your event is not called instead of postback so put your gridview binding statement in following block.
if (!Page.IsPostBack)
{
gridDepartement.DataSource = adp.GetDataDepartement();
gridDepartement.DataBind();
}
function SelectAll(objcheckbox)
{
var HeaderCBControl = objcheckbox;
//var table = getParentByTagName(HeaderCBControl, 'table');
var Inputs = document.getElementById('CenterContent_gridDepartement').getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox')
{
Inputs[n].checked = HeaderCBControl.checked;
}
return false;
}
</script>
I have the following piece of code. I did not define any boundfields in my gridview. I am retrieving data using sql queries in my aspx.cs file instead. Is it possible to adjust the width of each column 0, 1, 2? Are there any ways that I can look into? I have tried a lot of ways but it is still not working. Please help!
<asp:GridView ID="surgicalGridView" runat="server"
CaptionAlign="Top" HorizontalAlign="Justify"
DataKeyNames="id" onselectedindexchanged="surgicalGridView_SelectedIndexChanged"
ToolTip="Excel File Download Tool" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="854px">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Download"
ControlStyle-ForeColor="Blue">
<ControlStyle ForeColor="Blue"></ControlStyle>
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<br />
You can do that on the OnRowDataBound event of the gridview.
protected void surgicalGridView_RowDataBound(object o, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Width = new Unit("200px");
e.Row.Cells[1].Width = new Unit("400px");
// and so on
}
}
Add this to your Gridview Markup
<asp:GridView ...............................
onrowdatabound="surgicalGridView_RowDataBound"> // just add this event and execute the above code
</asp:GridView>
My solution is below. I have a grid that has 2 defined columns and the rest are bound dynamically. I don't know why setting the column with (e.Row.Cells[0].Width = new Unit("200px");) didn't work, but I found an alternative. Also, my grid has sorting enabled, therefore the linkbutton code.
const int FirstControl = 0;
const int GriDefinedFieldsCount = 2;
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
int col = 0;
foreach (DataColumn dc in SiteManager.Reports.ReportData.Columns)
{
if (dc.ColumnName == "Notes")
{
LinkButton lnk = (e.Row.Cells[col + GriDefinedFieldsCount].Controls[FirstControl] as LinkButton);
lnk.Width = Unit.Pixel(300);
}
col += 1;
}
}
As grid is rendered as table tr and dt so you can use the css class for the grid.
There you can set the width of your columns.
In classes your can use like td, td+td,td+td+td etc
According to the post
.NET Gridview themes examples
Check out these links.
http://icant.co.uk/csstablegallery/index.php?css=69#r69
http://mattberseth2.com/demo/ has lot of gridview customizations with code download.
Paging
Paging With Slider
Sorting with sort icons
Some more themes
http://mattberseth2.com/demo/Default.aspx?Name=A+YUI+DataTable+Styled+GridView&Filter=All
http://mattberseth.com/blog/2007/11/5_gridview_themes_based_on_goo.html
(source: mattberseth.com)