I Have a nested grid i want to check the column in grid when datakey is present in another table
Grid is like this
<asp:GridView Width="100%" DataKeyNames="PK_ServiceTypeID" HorizontalAlign="Center" runat="server" OnRowDataBound="gridServiceLocations_RowDataBound" AutoGenerateColumns="false" ID="gridServiceLocations" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../../Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" Width="100%" DataKeyNames="PK_ServiceDetailID">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Service" HeaderText="Service" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ServiceTypeName" HeaderText="ServiceTypeName" HeaderStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
i have binded this grid from code behind
If I understand I think something like that will be working :
First, you'll need clear data to work with : get the value from your sql column and store it into a string ( or any type you want) array or List, something like that :
//Get your column value from your db
string myValueFromDb = "0000000062,0000000034,0000000016,0000000174,0000000055";
//Split the values into an list of string
myValues = new List<string>(myValueFromDb.Split(','));
//Here you have all your db values stored in the list myValues
But to access to your checkBox you must add an ID.
Like : asp:CheckBox runat="server" ID="checkBox" />
Now you'll need to check every row of your gridview. Something like that :
protected void gridServiceLocations_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != -1)
{
//Get the value of the current row DataKey
string dataKey = grid_view.DataKeys[e.Row.RowIndex].Value.ToString();
//GET THE ROW
GridViewRow row = e.Row;
//Now compare it with your value
if (myValues.Contains(dataKey))
{
//CHECK CASE
//The index of column of the column where the checkbox are (1 here, change it )
CheckBox checkbox = ((CheckBox)row.Cells[1].FindControl("checkBox"));
checkbox.Checked = true;
}
else
{
//UNCHECK CASE
CheckBox checkbox = ((CheckBox)row.Cells[1].FindControl("checkBox"));
checkbox.Checked = false;
}
}
}
Related
I need to load the Checked Value in the column Status if the Value in the Attendance_Status = "Attended"
and uncheck if the value is Unattended.
Below is the screen shot of the form:
I am trying to add the code below but it doesn't work:
foreach (DataGridViewRow row in dataGridView2.Rows) {
if (row.Cells["Attendance_Status"].Value == "Attendance")
{
row.Cells["Status"].Selected = true;
}
else
{
row.Cells["Status"].Selected = false;
}
}
Please help!!
You can try with finding the control in the gridview and then the value of that checked either 0 or 1 based on whether it is selected or not as shown below.
foreach (GridViewRow row in gvGridview.Rows)
{
CheckBox cbAddAction = (CheckBox)row.FindControl("chkAddAction");
int addPermission = Convert.ToInt16(cbAddAction.Checked);
}
You can check the below gridview definition/declaration for more help.
<asp:GridView ID="gvUserPermission" runat="server" AllowPaging="True" AutoGenerateColumns="False"
CssClass="table table-striped table-bordered bootstrap-datatable" HorizontalAlign="Center"
OnRowDataBound="gvUserPermission_RowDataBound" PageSize="50"
DataKeyNames="ModuleId"
onselectedindexchanged="gvUserPermission_SelectedIndexChanged">
<PagerSettings FirstPageText="« First" LastPageText="Last »" Mode="NumericFirstLast"
PageButtonCount="10" />
<Columns>
<asp:BoundField DataField="Modulename" HeaderText="Module Name" ItemStyle-Width="450px"
SortExpression="Modulename" />
<asp:TemplateField HeaderText="Add Action">
<ItemTemplate>
<asp:CheckBox ID="chkAddAction" Checked='<%# Eval("AddAction") == DBNull.Value ? false : Convert.ToBoolean(Eval("AddAction")) %>'
runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
To load the data you can use the following method. It will check the value as per the data without any additional loop.
<asp:TemplateField HeaderText="Edit Action">
<ItemTemplate>
<asp:CheckBox ID="chkEditAction" Checked='<%# Eval("EditAction") == DBNull.Value ? false : Convert.ToBoolean(Eval("EditAction")) %>'
runat="server" />
</ItemTemplate>
</asp:TemplateField>
In your SQL Server datasource write a case statement to return NULL for values which is not Attended as given below.
create table Attendace (Id int, Attendance_Status Varchar(50))
insert into Attendace values (1, 'Attended'),
(2, 'Not Attended')
select id
, case Attendance_Status when 'Attended' then 1 else null
end as Attendance_Status
from Attendace
I've a Nested grid and check box in parent and child grid. There is a main checkbox at parent grid header to select all data. Then there is another check box against parent row and third check box against every child row.
first two checkboxes and events are working fine.
Issue is with child grid checkbox. when I check the checkbox the event gets fired as expected. But when the checkbox is unchecked the event doesn't get fired. instead it is just posting back.
Code is as below.
<asp:GridView ID="grdmaster" runat="server" SkinID="GridView" AutoGenerateColumns="false" DataKeyNames="ProjectNo" HorizontalAlign="Center" HeaderStyle-Height="35px" OnRowDataBound ="grdmaster_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="View Forging">
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus1.png" />
<asp:Panel ID="pnlforginfo" runat="server" Style="display: none">
<asp:GridView ID ="gvforgmst" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid" ShowHeaderWhenEmpty="true" EmptyDataText="No Data Found" SkinID="GridView">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="ForgingNo" HeaderText="Forging No" />
<asp:BoundField ItemStyle-Width="150px" DataField="ProductType" HeaderText="Product" />
<asp:TemplateField ControlStyle-Height="35px">
<ItemTemplate>
<asp:CheckBox ID="chkviewforg" runat="server" AutoPostBack ="true" OnCheckedChanged="chkviewforg_CheckedChanged" ViewStateMode="Enabled" EnableViewState="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="ProjectNo" DataField="ProjectNo" />
<asp:BoundField HeaderText="CustomerName" DataField="CustomerName" />
<asp:BoundField HeaderText="GradCode" DataField="GradCode" />
<asp:TemplateField ControlStyle-Height="35px">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server"
AutoPostBack="true" OnCheckedChanged="chkAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server"
AutoPostBack="true" OnCheckedChanged="chk_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void chkviewforg_CheckedChanged(object sender, EventArgs e)
{
int cnt = 0;
CheckBox chkAll = (CheckBox)grdmaster.HeaderRow.Cells[4].FindControl("chkAll");
for (int i = 0; i < grdmaster.Rows.Count; i++)
{
GridView gvforgmst = (GridView)grdmaster.Rows[i].FindControl("gvforgmst");
CheckBox chk = (CheckBox)grdmaster.Rows[i]
.Cells[4].FindControl("chk");
foreach (GridViewRow gr in gvforgmst.Rows)
{
CheckBox chkviewforg = ((CheckBox)gr.FindControl("chkviewforg"));
if (chkviewforg.Checked)
{
cnt++;
}
}
if (gvforgmst.Rows.Count > 0)
{
if (cnt == gvforgmst.Rows.Count)
{
chk.Checked = true;
}
else
{
chk.Checked = false;
chkAll.Checked = false;
}
}
}
}
I am getting an error on accessing gridview hidden field Ids while trying to save the gridview row details. What i want to do is to save the all gridview rows back to database. I am bit confused on accessing the value of the row ids. Please help me to overcome this problem.
<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ServiceID" Font-Names="Segoe UI Symbol" Font-Size="11pt" RowStyle-BackColor="#A1DCF2"
ShowFooter="true" Width="670px">
ForeColor="White" />
<PagerStyle CssClass="cssPager" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<%--ServiceID--%>
<asp:TemplateField HeaderText="ServiceID" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="lblServiceID" runat="server" Text='<%# Eval("ServiceId")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<%-- ServiceName --%>
<asp:TemplateField HeaderText="Service" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblService" runat="server" Text='<%# Eval("ServiceName")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="300px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
//Save TestDetails
foreach (GridViewRow rw in GridView1.Rows)
{
var n = new TestDetail
{
PriceListId = txtPriceList.text,
ServiceId = Convert.ToInt32(GridView1.DataKeys[rw.RowIndex].Value),
Price = Convert.ToDecimal(txtPrice.Text.ToString()),
};
using (var context = new DiagEntities())
{
context.TestDetail.Add(n);
context.SaveChanges();
}
}
You should use the DataKeys:
// Get the index of the current row.
int index = rw.RowIndex;
// Based on the index of the row
// get the DataKey value and convert it to an int
ServiceId = Convert.ToInt32(GridView1.DataKeys[index].Value);
How can I select all data from GridViews current row..
I have a column for edit link in GridView. When "Edit" link button is clicked, I want to use that selected row's data. I am trying the following code, but it's returning me with an empty value
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = -1;
GridViewRow gvRow = gv.Rows[ e.NewEditIndex];
string selectedID = gvRow.Cells[3].Text;
}
<asp:GridView runat = "server" ID="gvRange0" SkinID="gridView" AutoGenerateColumns="False"
AllowSorting="True" OnRowCancelingEdit="gvRange_RowCancelingEdit" OnRowDeleting="gvRange_RowDeleting"
OnRowEditing="gvRange_RowEditing" OnRowUpdating="gvRange_RowUpdating"
Width="684px" OnRowDataBound="gvRange_RowDataBound"
DataMember="DefaultView" OnPageIndexChanged="gvRange_PageIndexChanged"
OnPageIndexChanging="gvRange_PageIndexChanging" OnSorting="gvRange_Sorting" DataKeyNames = "RANGE_ID"
OnSelectedIndexChanged="gvRange_SelectedIndexChanged" Height="65px" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<ControlStyle Width="2px" />
<asp:LinkButton ID="lnkDelete0" runat="server" CssClass="lnk"
CausesValidation="False" CommandName="Delete"
Text="Delete" Visible="false"></asp:LinkButton>
<asp:CheckBox runat="server" ID="chkSelect" CssClass="lbl" Text="" AutoPostBack="False" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<controlStyle width="2px" />
<asp:LinkButton ID="lnkEdit" runat="server" CssClass="lnk" CausesValidation="False" CommandName="Edit"
Text="Edit" ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="5px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Ranges" SortExpression="Sort_Ranges">
<ControlStyle Width="5px" />
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"Min_Age") %>
<%# CheckNull(DataBinder.Eval(Container.DataItem,"Max_Age")) %>
</ItemTemplate>
<%-- <ItemTemplate>--%>
<%--<asp:Label ID="lblStageName" CssClass="lbl" runat="server" Text='<%# Bind("Age_Range") %>' Width="1px"></asp:Label>--%>
<%-- </ItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField HeaderText="Range ID">
<ItemTemplate><%#DataBinder.Eval(Container.DataItem,"RANGE_ID") %></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
There are 4 columns in the GridView. One contains check box, second is link button for edit, third databound with some value, fourth is the column which I want to use to get some values from database(that is primary key there) and this column is hidden.
sometime in gridview cell create child controls.
you can try this code. may be solve it.
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = -1;
GridViewRow gvRow= (GridViewRow)(((Button)e.CommandSource).NamingContainer);
foreach (TableCell Tc in gvRow.Cells)
{
//if you are not getting value than find childcontrol of TabelCell.
string sss = c.Text;
foreach (Control ctl in Tc.Controls)
{
//Child controls
Label lb = ctl as Label;
string s = lb.Text;
sb.Append(s + ',');
}
}
}
I've noticed that you say you need to access the 4th column but you're using gvRow.Cells[3].Text;
The indexing in the Cell object is done from 1, so if you need to access the 4th row in the grid view try this:
string selectedID = gvRow.Cells[4].Text;
EDIT:
Could you please confirm two things for me
1)When you click on lnkEdit is the GridView1_RowEditing event being raised?
2)If yes, is the e.NewEditIndex value always showing up as '0'?
Attempt clicking the edit link on different rows, is the result always '0'?
I have a gridview which displays the contents of a database table in rows. There is a CheckboxField there and a Select button. I want to set button visibility to false when checkboxfield is checked.
this is my aspx page:
<asp:DetailsView ID="DetailsViewERgo" runat="server" Height="50px"
Width="100%" AutoGenerateRows="False" CellPadding="4"
DataSourceID="LinqDataSourceErgo" ForeColor="#333333" GridLines="None"
HeaderText="Σύντομη Περιγραφή Επιλεγμένου Έργου">
<Columns>
<asp:CheckBoxField DataField="Diekperewsi" HeaderText="Answered"
SortExpression="Diekperewsi" Visible="True"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
<asp:TemplateField HeaderText="Insert Answer" ShowHeader="False">
<ItemTemplate>
<center>
<asp:Button ID="Button1" runat="server" CausesValidation="False"
CommandName="Select" Text="Επιλογή" Visible="true" >
</asp:Button>
</center>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have tried this but only works with checkboxes
protected void GridViewAitima_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.FindControl("Diekperewsi");
Button b = (Button)e.Row.FindControl("Button1");
if (!cb.Checked)
{
b.Visible = false;
}
else
{
b.Visible = true;
}
}
}
Your code will run on the server side but it looks as if the the AutoPostBack property for your checkbox is not set to true -
AutoPostBack="True"
so when the checkbox is checked the code will not run immediately, it will only run after another event has caused your page to postback.
CheckBoxField has no id thus you can't find it by id, moreover it has no value propertie.
I suggest you use template field just like you used for the button, but instead put a checkbox in it.
so instead of :
<asp:CheckBoxField DataField="Diekperewsi" HeaderText="Answered"
SortExpression="Diekperewsi" Visible="True"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
put :
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Diekperewsi" Enabled="false" Checked='<%#Eval("Diekperewsi")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
and you are good