GridView Row checkboxes - c#

I have a gridview in my .NET web app:-
<asp:GridView ID="gvwQueues" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="gvwQueues_PageIndexChanging"
PageSize="5" Width="577px">
<Columns>
<asp:BoundField DataField="Text" HeaderText="Text">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ItemNumber" HeaderText="Item Number">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Directory" HeaderText="Directory">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate>
<asp:CheckBox ID="Yes" runat="server" Text = "Yes" />
<asp:CheckBox ID="No" runat="server" Text = "No"/>
<%-- <asp:CheckBoxList ID="IsActive" runat="server">
<asp:ListItem>Yes.</asp:ListItem>
<asp:ListItem>No.</asp:ListItem>
</asp:CheckBoxList>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now I want to use the checkboxes:- "yes" or "no" to call appropriate functions on the server side that would make each item on the gridview row "Active" or "inactive".
Active means the item shows up for all users, Inactive means the item doesnt show up for any users, except for the admin.

Two modifications might me needed to make your logic work.
a. Try using Radiobutton in the place of using Check Boxes so that the user will be able to select ONLY ONE OPTION either 'Yes' or 'No'. Also note you need group these radio buttons like below to let only one of these radio buttons selectable. So replace your 'IsActive' template field with below:
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate>
<asp:RadioButton ID="yesRadioButton" runat="server" Text="Yes" GroupName="IsActiveGroup" OnCheckedChanged="RadioButtonIsActive_CheckedChanged" />
<asp:RadioButton ID="noRadioButton" runat="server" Text="No" GroupName="IsActiveGroup" OnCheckedChanged="RadioButtonIsActive_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
And assign both of its CheckChanged event to RadioButtonIsActive_CheckedChanged method.
b. Below is the code for the Code behind mehtod RadioButtonIsActive_CheckedChanged
protected void RadioButtonIsActive_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gvwQueues.Rows)
{
RadioButton yesRadioButton = (RadioButton)row.FindControl("yesRadioButton");
if (yesRadioButton.Checked)
{
//Make Items Active
}
else
{
//Make Items Inactive
}
}
}
Let me know in case of any queries.

Do you want the check box to call a function when it changes?
Then all you need to do is add OnCheckedChanged
<asp:CheckBox ID="chkStatus" runat="server" Text = "Yes"
OnCheckedChanged="chkStatus_OnCheckedChanged"/>
Serverside you write the function you want it to do
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
//Make active inactive
}
Out side of this are you asking about roles, or binding to a grid?

you can use DataKeyNames for the grid view.
try this once.
<asp:GridView ID="gvwQueues" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="gvwQueues_PageIndexChanging"
PageSize="5" Width="577px" DataKeyNames="ItemNumber">
<Columns>
<asp:BoundField DataField="Text" HeaderText="Text">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ItemNumber" HeaderText="Item Number">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Directory" HeaderText="Directory">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate>
<asp:CheckBox ID="chkYes" runat="server" Text="Yes" OnCheckedChanged="YesOrNo_OnCheckedChanged"
AutoPostBack="true" />
<asp:CheckBox ID="chkNo" runat="server" Text="No" OnCheckedChanged="YesOrNo_OnCheckedChanged"
AutoPostBack="true" />
<%-- <asp:CheckBoxList ID="IsActive" runat="server">
<asp:ListItem>Yes.</asp:ListItem>
<asp:ListItem>No.</asp:ListItem>
</asp:CheckBoxList>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And you can catch the Item Number using ClientID of sender argument
protected void YesOrNo_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkSender = (CheckBox)sender;
foreach (GridViewRow gvRow in gvwQueues.Rows)
{
if (gvRow.RowType == DataControlRowType.DataRow)
{
CheckBox chkYes = (CheckBox)gvRow.FindControl("chkYes");
CheckBox chkNo = (CheckBox)gvRow.FindControl("chkNo");
if (chkSender.ClientID == chkYes.ClientID || chkSender.ClientID == chkNo.ClientID)
{
int ItemId = Convert.ToInt32(gvwQueues.DataKeys[gvRow.RowIndex].Value);//here is the item number
if (chkNo.Checked)
{
chkYes.Checked = false;
//code to inactive
}
else if (chkYes.Checked)
{
chkNo.Checked = false;
//code to activate
}
}
}
}
}
One more suggestion is better to use Radiobuttons instead of Checkboxes.
You need to handle many conditions by using Checkboxes in your case.

Related

How to get cell value in a GridView on LinkButton Click Event? Or RowCommand?

I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}

Delete GridView Rows in button cick without RowDeleting that not saved in DB

I have a gridview,
When Button ADD is clicked the textboxs values will be added to gridview.
After adding values to gridview i want to select a row and click delete button but error occurs to me on deleting.
My GridView Code
<asp:GridView ClientIDMode="Static" ID="GridPesonal" runat="server" AutoGenerateColumns="False" Class="GrdSty" Width="100%" DataKeyNames="RowNumber">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="ردیف">
</asp:BoundField>
<asp:BoundField DataField="StartDate" HeaderText="از تاریخ">
</asp:BoundField>
<asp:BoundField DataField="EndDate" HeaderText="تا تاریخ">
</asp:BoundField>
<asp:BoundField DataField="SherkatName" HeaderText="نام شرکت،سازمان یا موسسه" >
</asp:BoundField>
<asp:BoundField DataField="WorkUnitName" HeaderText="واحد محل کار">
</asp:BoundField>
<asp:BoundField DataField="Sharh" HeaderText="شرح دقیق شغل/سمت/مسئولیت" >
</asp:BoundField>
<asp:BoundField DataField="WorkTime" HeaderText="زمان کار" >
</asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="توضیحات">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="SavabegSelect" runat="server" AutoPostBack="True" OnCheckedChanged="SavabegSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
موردی ثبت نشده است.
</EmptyDataTemplate>
</asp:GridView>
Btn Delete Code
<asp:Button ClientIDMode="Static" ID="BtnDelete" CssClass="btnregister" runat="server" Text="حذف" OnClick="BtnDelete_Click" />
Code behind of btn Delete
protected void BtnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridPesonal.Rows)
{
CheckBox chkdelete = (CheckBox)gvrow.FindControl("SavabegSelect");
if (chkdelete.Checked)
{
GridPesonal.DeleteRow(gvrow.RowIndex);
}
}
}
When execute above code this error show
The GridView 'GridPesonal' fired event RowDeleting which wasn't handled.
Have you used command-name as Delete on BtnDelete.
Remove that from Delete Button it will work.
If you have like this
<asp:GridView ID="gvRoute" DataKeyNames="Route" runat="server" AutoGenerateColumns="false"
AllowPaging="true" Width="30%"
onrowdeleting="gvRoute_RowDeleting">
Remove onrowdeleting="gvRoute_RowDeleting
or wirte event for
protected void gvRoute_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
\\
}
or Use the "CommandName" property "Delete"
Or Use OnClick
<asp:GridView ClientIDMode="Static" ID="GridPesonal" runat="server" AutoGenerateColumns="False" Class="GrdSty" Width="100%" DataKeyNames="RowNumber" OnClick="BtnDelete">

One-way databind gridview - Update only?

I'm doing some complicated things with a gridview and the only thing standing between me and completion is the fact that I can't set the databinding programmatically. I've made it most of the way around this issue except that I still cannot get the datasource to update.
I've replaced one input field with a dependent dropdownlist and gotten it to retain the value of the field on databind. I can't databind it directly because I get 'Selected Value not in list of items' or something, so I have to find a way to get the grid or the datasource to take the value from this dependent drop down and apply it to the table.
Any help?
<asp:GridView ID="gvManager" runat="server"
AutoGenerateColumns="False" DataSourceID="ldsCampaigns"
ondatabound="gvManager_DataBound"
onrowediting="gvManager_RowEditing" DataKeyNames="ContentID">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="ContentID" HeaderText="ContentID"
SortExpression="ContentID" />
<asp:BoundField DataField="CampaignName" HeaderText="CampaignName"
SortExpression="CampaignName" />
<asp:BoundField DataField="CampaignTitle" HeaderText="CampaignTitle"
SortExpression="CampaignTitle" />
<asp:BoundField DataField="CampaignTagLine" HeaderText="CampaignTagLine"
SortExpression="CampaignTagLine" />
<asp:TemplateField HeaderText="CampaignData" SortExpression="CampaignData">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="ldsTables"
DataTextField="CMSTables" DataValueField="CMSTables"
SelectedValue='<%# Bind("CampaignData") %>' onload="DropDownList1_Load">
</asp:DropDownList>
<asp:LinqDataSource ID="ldsTables" runat="server"
ContextTypeName="DataContext"
onselecting="ldsTables_Selecting" Select="new (CMSTables)"
TableName="CampaignTables">
</asp:LinqDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CampaignData") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DataColumn"
SortExpression="DataColumn">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" style="margin-bottom: 0px"
SelectedValue='<%# Bind("DataColumn") %>' Visible="False">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("DataColumn") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CampaignLink" HeaderText="CampaignLink"
SortExpression="CampaignLink" />
<asp:BoundField DataField="Sunrise" HeaderText="Sunrise"
SortExpression="Sunrise" />
<asp:BoundField DataField="Sunset" HeaderText="Sunset"
SortExpression="Sunset" />
<asp:BoundField DataField="OwnerID" HeaderText="OwnerID"
SortExpression="OwnerID" />
<asp:CheckBoxField DataField="Enabled" HeaderText="Enabled"
SortExpression="Enabled" />
</Columns>
</asp:GridView>
If i understood you question right, you have a gridview and inside the gridview there is a dropdownlist, on changing the dropdownlist you want to get it's value and fetch some data or whatever you want with it, if that is the case then what you haved is the following:
1-Set your dropdownlist property AutoPostBack = "true".
2-On the dropdownlist_indexchanged event for the dropdownlist do the following:
protected void dropdownlist1_indexchanged(sender object,eventargs e)
{
//Because the dropdownlist is inside the gridview you can't get data directly
//You will have to parse the sender object which will retrieve the dropdownlist
DropdownList ddl = (DropdownList)sender;
//You can then extract the data from the dropdownlist
}
For any future desperate programmer, I had to update the linq data source code on the updated event:
protected void ldsCampaigns_Updated(object sender, LinqDataSourceStatusEventArgs e)
{
using (DashboardDataContext c = new DashboardDataContext())
{
Label Label3 = gvManager.Rows[gvManager.EditIndex].FindControl("Label4") as Label;
List<CMSCampaigns> change = c.CMSCampaigns.Where(s => s.ContentID == Convert.ToInt16(Label3.Text)).ToList();
DropDownList DropDownList2 = gvDashboardManager.Rows[gvDashboardManager.EditIndex].FindControl("DropDownList2") as DropDownList;
change[0].DataColumn = DropDownList2.SelectedValue.ToString();
c.SubmitChanges();
}
}
This is the clusteriest clusterkludge I've ever kludgestergrammed.

Checkboxfield value controls button visibility

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

How to edit an entire column for all rows asp:GridView

So I have google'd and searched stackoverflow, and now my brain is overloaded. I am a novice at asp.net, but getting the hang of it.
My current requirement is to have a gridview where upon load, 1 column for all rows is immediately placed into edit mode. I used this question and code to get me going:
Allowing one column to be edited but not another
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
allowpaging="true"
datakeynames="CustomerID"
runat="server">
<columns>
<asp:boundfield datafield="CustomerID" readonly="true" headertext="Customer ID"/>
<asp:boundfield datafield="CompanyName" readonly="true" headertext="Customer Name"/>
<asp:boundfield datafield="Address" headertext="Address"/>
<asp:boundfield datafield="City" headertext="City"/>
<asp:boundfield datafield="PostalCode" headertext="ZIP Code"/>
</columns>
</asp:gridview>
I have searched and found a few good solutions, however, I do not fully understand them and have been unsuccesful at implementing them. They are:
Edit/Update a single GridView field
Put multiple rows of a gridview into edit mode
So my question is, how would you go about placing a column, (e.g, ZIP Code) into edit mode for all rows at the same time?
All help is appreciated!
Thanks!
Stephen
You won't be able to use the built-in edit functionality, but you can achieve this by loading the column in edit mode using a TemplateField:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("SomeColumn") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SomeOtherColumn" HeaderText="Foo" />
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Update" CommandArgument='<%# Container.ItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = GridView1.Rows[(int)e.CommandArgument];
if (row != null)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}
EDIT: Putting a button outside of the GridView, you would update like this:
<asp:GridView>
...
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}

Categories

Resources