I want to display data in gridview based on check box selection from another grid view. The given below code getting values into from first gridview based on check box selection. I want to bind that values into second grid. Help me to find a proper solution. Thank you.
Code :
protected void btnAssign_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
string[] EmpId = new string[] { row.Cells[0].Text };
string[] EmpName = new string[] { row.Cells[1].Text};
// I want to display emp id and emp name on gridview 2 based on check box selection. How can I do. Help me to find a proper solution
GridView2.DataSource = EmpId;
GridView2.DataBind();
}
}
}
}
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="FirstName" HeaderText="Employee Name" ReadOnly="True" SortExpression="FirstName" />
<asp:TemplateField HeaderText="Select" SortExpression="Select">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server"> </asp:GridView>
The given below image is showing data in grid view based on drop-down selection. After that I want to select some rows and click assign then I have to display the selected rows in new gridview.
Image :
If you don't already have a strong type defined to represent your selected Employee, you could create a Dictionary to store your selected employees. Upon completing your iteration over GridView1's rows to get the selected employees, you could use the dictionary as the datasource for GridView2 and bind to the Key and Value of each entry.
protected void btnAssign_Click(object sender, EventArgs e)
{
Dictionary<int, string> selectedEmployees = new Dictionary<int, string>();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
selectedEmployees.Add(int.Parse(row.Cells[0].Text), row.Cells[1].Text);
}
}
}
if (selectedEmployees.Any())
{
gridView2.DataSource = selectedEmployees;
gridView2.DataBind();
}
}
UPDATE: Updated the code to account for the exception that you were receiving with the sample code provided
Related
I have a DataGridView with a column which with button.
Now I want that with every click on the button the selected row in the DataGridView is copied and inserted directly after the selected row.
I want to duplicate all value of all columns and insert into table of my database this new row.
How can I realize this ?
Many thanks in advance.
On my code below the error is on this line
cgv.Rows.Add(gvRow.Cells[1].Text);
<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="btselect" runat="server"
CommandName="Select"
OnClick="Copy"
ImageUrl="/aspnet/img/clone_icon.gif"
ToolTip="Clone row" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerId" HeaderText="ID" />
</Columns>
</asp:GridView>
protected void Copy(object sender, EventArgs e)
{
GridViewRow gvRow = this.gvProducts.SelectedRow;
DataTable cgv = null;
if (ViewState["Customers"] != null)
{
cgv = ViewState["Customers"] as DataTable;
cgv.Rows.Add(gvRow.Cells[1].Text);
ViewState["Customers"] = cgv;
}
BindData();
}
protected void gvProducts_SelectedIndexChanged(object sender, EventArgs e)
{
this.gvProducts.SelectedRow.BackColor = System.Drawing.Color.Cyan;
}
Ok, you are in a good place in that you attempting to add the data row to the data source, or the datatable that you are persiting in session.
So, I would do it this way:
protected void Copy(object sender, EventArgs e)
{
GridViewRow gvRow = this.gvProducts.SelectedRow;
DataTable cgv = null;
if (ViewState["Customers"] != null)
{
cgv = ViewState["Customers"] as DataTable;
DataRow MyNewRow = cgv.NewRow()
MyNewRow["FirstName"] = gvRow.Cells[2].Text;
MyNewRow["LastName"] = gvRow.Cells[3].Text;
MyNewRow["CustomerID"] = gvRow.Cells[0];
cgv.Rows.Add(MyNewRow);
ViewState["Customers"] = cgv;
}
BindData();
}
Do remember that any template field in the GV needs to use find control, but from what you posted, it does look like using .cells[] collection should work for you.
I am able to retrieve out data from database to show which is Y and N using checkbox in gridview. However now i want to to able to store which checkbox is checked back into the database after editing.
What i did so far:
.aspx
<asp:GridView ID="SiteGridView" runat="server" CssClass="datagrid"
GridLines="Vertical" AutoGenerateColumns="False"
Width="100%"
AllowPaging="True" AllowSorting="True"
DataKeyNames="promoID" OnRowCommand="GvPage_RowCommand"
OnPageIndexChanging="GvPage_PageIndexChanging"
OnSorting="GvPage_Sorting"
OnRowDatabound="SiteGridView_RowDataBound"
OnRowEditing="SiteGridView_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Default">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server"
Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>' />
</ItemTemplate>
<ItemStyle Width="20%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind:
SqlCommand cmd = new SqlCommand("SELECT * , CAST(CASE defaults WHEN 'Y' THEN 1 ELSE 0 END AS BIT) AS PROCESSED FROM Promotions");
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
// Save results of select statement into a datatable
da.Fill(dt);
SiteGridView.DataSource = dt;
SiteGridView.DataBind();
protected void SiteGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check userrole & display accrodingly
if (Session["ROLE"].ToString() != "SA")
{
//ImageButton btnEdit = (ImageButton)e.Row.FindControl("btnDelete");
//btnEdit.Visible = false;
SiteGridView.Columns[4].Visible = false;
}
}
}
Have you tried:
Checked='<%# Eval("PROCESSED")%>'
If so, what error messages have you gotten?
For some reason Checkboxes do not trigger GridView RowCommand events. It probably can be done with appropriate calls to ClientScript.GetPostBackEventReference(), but thats a whole other level of complexity. So, in order to act on a CheckBox click and handle events individually:
(NB: I've stripped out much of your coding to clarify my points.)
In your CheckBox set AutoPostBack="true"
Add a handler for OnCheckedChanged.
Make sure the DataKey contains the pk of the row you need to update with the CheckBox State
// Simplified version of your markup
<asp:GridView ID="SiteGridView" runat="server"
DataKeyNames="promoID"
OnRowDataBound="SiteGridView_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Default">
<ItemTemplate>
<asp:CheckBox ID="process_flag" runat="server"
Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>'
OnCheckedChanged="process_flag_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the RowDataBound event, find the CheckBox and add the Row Index as an attribute
// Merge this with your `RowDataBound` event
protected void SiteGridView_RowDataBound( object sender, GridViewRowEventArgs e ) {
if ( e.Row.RowType == DataControlRowType.DataRow ) {
CheckBox cbx = ( CheckBox ) e.Row.FindControl( "CheckBox1" );
cbx.Attributes[ "data-row-idx" ] = e.Row.RowIndex.ToString();
}
}
Handle the CheckChanged event:
// Add this handler to your code
protected void process_flag_CheckedChanged( object sender, EventArgs e )
{
CheckBox cbx = ( CheckBox ) sender;
Int32 rowidx = Convert.ToInt32(cbx.Attributes["data-row-idx"]);
Int32 pk = (Int32) GridView4.DataKeys[rowidx].Value;
// simple way to see event arguments before actually touching the database
GridView4.Caption = string.Format(
"CheckChanged: Row {0}, State: {1}, RowPK: {2} ", rowidx , (cbx.Checked ? "Checked" : "Unchecked"), pk );
// Save Data and rebind the gridview to reflect changes
// Verify your parameters before attempting an actual update
// YourDatabaseCallWithAppropriateParamaters( ... );
GridView1.DataBind();
}
First of all use a foreach loop to findout which rows are checked. Then store ID of those rows in a List.
foreach (GridViewRow row in SiteGridView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("process_flag") as CheckBox);
if (chkRow.Checked)
{
string ID = row.Cells[columnID].Text;
I have written code like below lines of code
protected void grdView_DataBinding(object sender, EventArgs e)
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, LicenseType);
foreach (GridViewRow row in grdView.Rows)
{
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
TextBox txtDateIssued = row.FindControl("txtEffectiveDate") as TextBox;
TextBox txtDateExpiration = row.FindControl("txtExpirationDate") as TextBox;
TextBox txtLicenseNumber = row.FindControl("txtLicenseNumber") as TextBox;
for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
{
txtLicenseNumber.Text = lds.Tables[0].Rows[i]["LicenceNumber"].ToString();
}
}
}
I want to bind grid view without using datasource property of gridview. The above code is not working...
Let's Suppose lds contains data like
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Similarily Grid will also contain the data
=====================================================
LicenceNumber - LicenceIssueDate
123 - 12/10/2014
345 - 12/1/2013
=====================================================
Here is grid view's design
<asp:GridView ID="grdView" AutoGenerateColumns="false" OnDataBinding="grdView_DataBinding" BorderWidth="0" runat="server" CssClass="table">
<Columns>
<asp:TemplateField HeaderText="License Number">
<ItemTemplate>
<asp:TextBox ID="txtLicenseNumber" style="padding:12px 5px;" runat="server" />
<br />
<asp:RequiredFieldValidator ID="ValReqLN" Display="Dynamic" runat="server"
ErrorMessage="License Number cannot be Blank." ControlToValidate="txtEffectiveDate"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Effective Date">
<ItemTemplate>
<asp:TextBox ID="txtEffectiveDate" style="padding:12px 5px;" placeholder="(mm/dd/yyyy)" CssClass="datepiker" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Please help!!!
Why would you not use datasource property ? you said: "i want to bind gridview programically because I have to give many conditions inside gridview's rows according to business logic in order to display data in the gridview.
Here is how you can do that:
Code behind:
protected void grdView_DataBinding(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv["txtLicenseNumber"].ToString().ToLower() == "abc")
{
//Apply business logic here on each row, hide/show etc
e.Row.CssClass = "highlighted";
}
}
}
Read more here on:
Dynamically change GridView Cell value using RowDataBound event in ASP.Net using C# and VB.Net
Selectively apply css to a row in a gridview
We have a webform with a radgrid and a button. The radgrid has two columns and a checkbox column.
On Page_load, the data will be displayed and the user will be able to select (via the checkbox) which rows will go through with the update of the EmpId; if the row is selected, NewEmpId will replace OldEmpId. The Update button is clicked and the changes are made.
The problem I'm having is that I prefer to use the datakeynames to retrieve the data from each row. But I'm having trouble implementing it without using GridCheckBoxColumn, which I don't want to use because the radgrid needs to be in Edit mode for the checkbox to be selected, and that brings other issues.
<telerik:RadGrid ID="RadGridEmp" runat="server" AutoGenerateColumns="False" Width="100%" AllowPaging="True" PageSize="22">
<ClientSettings>
<Selecting AllowRowSelect="True" />
</ClientSettings>
<mastertableview commanditemdisplay="TopAndBottom" datakeynames="OldEmpId, NewEmpId, EmpName">
<commanditemsettings showaddnewrecordbutton="false" />
<Columns>
<telerik:GridBoundColumn DataField="OldEmpId" HeaderText="OldEmpId">
<HeaderStyle Width="110px"></HeaderStyle>
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="NewEmpId" HeaderText="NewEmpId">
<HeaderStyle Width="110px"></HeaderStyle>
</telerik:GridBoundColumn>
<ItemTemplate>
<asp:CheckBox ID="ChkChange" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</mastertableview>
</telerik:RadGrid>
The following code is just the code I prefer to use with this issue. It uses datakeynames. But it doesn't build:
protected void RadButtonUpdateSectors_Click(object sender, EventArgs e)
{
foreach (GridItem item in RadGridEmp.MasterTableView.Items)
{
GridDataItem dataitem = (GridDataItem)item;
TableCell cell = dataitem["GridCheckBoxColumn"];
CheckBox checkBox = (CheckBox)cell.Controls[0];
if (checkBox.Checked)
{
oldEmpId = dataitem.GetDataKeyValue("OldEmpId").ToString();
newEmpId = dataitem.GetDataKeyValue("NewEmpId").ToString();
UpdateEmpId(oldEmpId, newEmpId, connString);
}
}
}
Please try with the below code snippet.
datakeynames="OldEmpId,NewEmpId,EmpName"
...............
...............
protected void RadButtonUpdateSectors_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGridEmp.MasterTableView.Items)
{
CheckBox ChkChange = item.FindControl("ChkChange") as CheckBox;
if (ChkChange.Checked)
{
string oldEmpId = item.GetDataKeyValue("OldEmpId").ToString();
string newEmpId = item.GetDataKeyValue("NewEmpId").ToString();
UpdateEmpId(oldEmpId, newEmpId, connString);
}
}
}
Let me know if any concern.
Note:- Remove extra space from datakeynames.
I want to change the text/value of a cell in certain condition in GridView. I have a cell that return 'P', 'A', 'R' when I bind the Gridview from database. I want to show 'Pending' in case of 'P', 'Approved' in case of 'A' and 'Rejected' in case of 'R' in the dropdown with the update button. I want to change the status of a record.
How can I change the text AND do my required task at the time of Binding of data.
<asp:TemplateColumn>
<HeaderStyle CssClass="bgB white p5 b treb ttu w10" />
<HeaderTemplate>
<asp:Label ID="lblstatus" runat="server" Text="Status"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblrmastatus" runat="server" Text='<%# Bind("RMA_STATUS") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
A way to solve this is to handle the RowDataBound event. It is raised once per row (also header and footer rows, so you need to filter for rows of type DataRow). You can use it to adjust the data that are displayed or the way they are displayed. Also you can set the values of a DropDown in the event. See the link for a sample.
In order to add the DropDown-column to the GridView, use a TemplateColumn and put the DropDown into the ItemTemplate. Access the corresponding cell in the RowDataBound event handler. Use the FindControl method to retrieve the DropDown control and set its values.
The following sample shows how to set the Label and the DropDownList programmatically:
GridView
The GridView shows both the original status and a new status with the long text, a DropDownList and a command column to update the data.
<asp:GridView ID="gdv" runat="server"
OnRowDataBound="gdv_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RMAStatus" HeaderText="Original RMA Status" />
<asp:TemplateField HeaderText="Adjusted RMA Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="New Status">
<ItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
Code-behind
In Code-behind, I've defined a class called DataClass that contains the data (you can also use a DataTable, but for the sample it was easier to use a class to generate some data). Also, a dictionary contains the mappings from the short status to the long text.
In Page_Load, the dictionary is set up and if it is no PostBack, the data are bound.
Finally, in gdv_RowDataBound, the label is set for each row and the DropDownList is initialized. Please note that the Label and the DropDownList for the row are retrieved by using FindControl.
public class DataClass
{
public string RMAStatus { get; set; }
}
private readonly Dictionary<string, string> rmaStatusMappings = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
rmaStatusMappings.Add("R", "Rejected");
rmaStatusMappings.Add("A", "Approved");
rmaStatusMappings.Add("P", "Pending");
if (!IsPostBack)
{
var data = new DataClass[] {
new DataClass() { RMAStatus = "P" },
new DataClass() { RMAStatus = "A" },
new DataClass() { RMAStatus = "R" },
new DataClass() { RMAStatus = "P" },
};
gdv.DataSource = data;
gdv.DataBind();
}
}
protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var rowStatus = ((DataClass)e.Row.DataItem).RMAStatus;
// Set label to long status
var lblStatus = e.Row.Cells[1].FindControl("lblStatus") as Label;
if (lblStatus != null)
lblStatus.Text = rmaStatusMappings[rowStatus];
// Set drop down items
var ddlStatus = e.Row.Cells[2].FindControl("ddlStatus") as DropDownList;
if (ddlStatus != null)
{
ddlStatus.DataTextField = "Value";
ddlStatus.DataValueField = "Key";
ddlStatus.DataSource = rmaStatusMappings;
ddlStatus.DataBind();
ddlStatus.SelectedValue = rowStatus;
}
}
}
Let me know in the comments if you have any questions.