I have a Grid1 with check box, Now I want to store Grid1 selected values into another grid grid2. How can I do this?
My Grid1 is
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" DataKeyNames="ShiftID"
Width="177px" onrowdatabound="GridView1_RowDataBound1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChbGrid" runat="server" oncheckedchanged="ChbGrid_CheckedChanged" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChbGridHead" runat="server" AutoPostBack="True"
Font-Bold="True" oncheckedchanged="ChbGridHead_CheckedChanged" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Gridview2 is
<asp:GridView ID="GridView2" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2">
</asp:GridView>
I have some function
protected void ChbGrid_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkstatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)checkstatus.NamingContainer;
}
protected void ChbGridHead_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkheader = (CheckBox)GridView1.HeaderRow.FindControl("ChbGridHead");
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkrow = (CheckBox)row.FindControl("ChbGrid");
if (chkheader.Checked == true)
{
chkrow.Checked = true;
{
}
}
else
{
chkrow.Checked = false;
}
}
}
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
}
What changes I should made to get my expected output. My GridView1 conatins ShiftID,ShiftName,ShiftTime and Date. How to generate query to dispaly selected Gridview1 item in Griview2
Write this in Source file
<asp:Button ID="btnGetSelected" runat="server" Text="Get selected records" OnClick="GetSelectedRecords" />
On the click of the Button the following event handler is executed. A loop is executed over the GridView Data Rows and CheckBox is referenced.
protected void GetSelectedRecords(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
string name = row.Cells[1].Text;
string country = (row.Cells[2].FindControl("lblCountry") as Label).Text;
dt.Rows.Add(name, country);
}
}
}
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
For more information us this links
GridView with CheckBox: Get Selected Rows in ASP.Net
Transfer Selected Rows from one GridView to Another in Asp.net
Related
I have a GridView that I populate. It appears correctly and shows the data. It contains a Checkbox column, and my intent is when the user clicks a button on the form, it iterates through the rows of the GridView, and totals up all the rows the user has selected by checking the CheckBox.
(I got the details of how to do this from http://asp.net-informations.com/gridview/checkbox.htm)
The problem comes at this point, and I've discovered that just before it gets to the line
foreach (GridViewRow row in grdItems.Rows)
grdItems.Rows.Count = 0, even though the GridView is currently displaying data.
The GridView:
<asp:GridView ID="grdItems" AutoGenerateColumns="false" runat="server" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkCtrl" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Item_No" HeaderText="Item No" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
</Columns>
</asp:GridView>
The Button:
<asp:Button ID="cmdOK" runat="server" Text="Add" />
The Button Onclick:
protected void cmdOK_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
SaveP2P();
}
}
The method the populates the GridView:
private void FillGrid()
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Snipped for privacy");
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandText = "Snipped for privacy";
cmd.Connection = conn;
System.Data.OleDb.OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter(cmd);
System.Data.DataSet ds = new System.Data.DataSet();
adp.Fill(ds);
adp.Dispose();
cmd.Dispose();
conn.Close();
grdItems.DataSource = ds;
grdItems.DataBind();
}
The ValidateForm() method which contains the code I'm struggling with
private bool ValidateForm()
{
bool result = true;
decimal TotalAmount = 0;
//If I display a message here, it shows grdItems.Rows.Count is 0
foreach (GridViewRow row in grdItems.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
TotalAmount += Decimal.Parse(row.Cells[2].Text);
}
}
}
decimal amount;
if (decimal.TryParse(txtAmount.Text, out amount))
{
if (amount > TotalAmount)
{
result = false;
}
}
else
{
result = false;
}
return result;
}
This sounds like a viewstate issue where when the page is posting back to the server, it is losing all the data in the grid. Have you tried enabling viewstate on your page to see if the gridview rows are returned.
protected void select_click(object sender, GridViewCommandEventArgs e)
{
try
{
DBLibrary db = new DBLibrary();
int index = Convert.ToInt32(e.CommandArgument);
* string FeeId = gridv1.Rows[index].Cells[1].Text;*
if (e.CommandName == "Select")
{
string str = "SELECT AnuFeeMaster.FeeId ,AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.FeeId ='" + FeeId + "')";
SqlDataReader dr = db.ExecuteReader(str);
while (dr.Read())
{
Session["name"] = dr["sname"].ToString();
Session["id"] = dr["StudentId"].ToString();
Session["mth"] = dr["Month"].ToString();
Session["yr"] = dr["Year"].ToString();
Session["tot"] = dr["FeeAmount"].ToString();
}
}
}
catch { }
}
Above is my code what i used to access that i am not getting the value r data from dat Please suggest me, * mark which i used that show where i am getting the error
create proper grid rowcommand Event
aspx code
<asp:GridView ID="Gv" runat="server" AllowPaging="true" OnRowCommand="Gv_RowCommand" PageSize="10" EmptyDataText="No Records Found !">
<Columns>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="20%">
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandArgument='<%#Eval("Demo_Code") %>' CommandName="select" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Coulmn1" HeaderText="Coulmn2" />
<asp:BoundField DataField="Coulmn2" HeaderText="Coulmn2" />
</Columns>
</asp:GridView>
aspx.cs Code
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
}
}
You should properly use RowCommand event of gridview.
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
You can catch the button click event like below:
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
This is my first time for using ASP.NET to develop website.
I want to show my data from database in a GridView with Paging function and I can implement it by using OnPageIndexChanging="GridView1_PageIndexChanging" but I want to use my own pager so the question is
"How can I link my pager (the right bottom in the pic) to the gridview instead the pager which generated by the ASP.NET"
Pics:
This is my code in aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-condensed table-striped table-primary table-vertical-center"
PageSize="3" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="UNIT_ID" HeaderText="รหัส" SortExpression="unitid">
<HeaderStyle CssClass="center" />
<ItemStyle Width="10%" CssClass="center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code in cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
protected void bindGridView() {
string sqltxt = "select * from drug_units"; //where UNIT_ID =:unitid";
CommandData comm = new CommandData();
comm.SetCommandText(sqltxt);
//comm.AddInputParameter("unitid", "5");
List<DrugsUnit> dy = new List<DrugsUnit>();
comm.ExecuteNonQuery();
dy = comm.ExecuteToList<DrugsUnit>();
GridView1.DataSource = dy;
/*BoundField boundField = new BoundField();
boundField.DataField = "UNIT_ID";
boundField.HeaderText = "ID";
boundField.SortExpression = "ID";
boundField.HeaderStyle.CssClass = "center";
boundField.ItemStyle.CssClass = "center";
GridView1.Columns.Add(boundField);*/
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
upGridPager.Update();
e.Row.SetRenderMethodDelegate(new RenderMethod((w, r) =>
{
e.Row.SetRenderMethodDelegate(null);
using (var ms = new StringWriter())
using (var writer = new HtmlTextWriter(ms))
{
e.Row.RenderControl(writer);
GridPager.InnerHtml = "<table>" + ms.ToString() + "</table>";
}
}));
}
The aspx could look like this (outside of your grid)
<asp:UpdatePanel ID="upGridPager" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div runat="server" id="GridPager" />
</ContentTemplate>
</asp:UpdatePanel>
I wants to enable or disable linkbutton on some rows of gridview based on condition.. Can i enable linkbutton on one row and disable it on another row of same grid view ??my code is here
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlCommand cmd12 = new SqlCommand("Select testsession_status from student_vs_testsession_details where testsession_id='" + v_testid.Text + "' ", con12);
SqlDataReader dr12 = cmd12.ExecuteReader();
while (dr12.Read())
{
string test_status = dr12[0].ToString();
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
foreach (GridViewRow row in GridView1.Rows)
{
if (v_testtype == "Theory Test" && test_status == "Completed")
{
lnk2.Visible = true;
}
else
{
lnk2.Visible = false;
}
}
}
Yes you can easily do it in RowdataBound Event, but you have used lnk2.Visible property in your code.
you may be using Visible property for another requirement but just want to confirm you that it is used to show/hide the Linkbutton only. To enable/disble a Linkbutton, use Enabled property of Linkbutton. as:
lnk2.Enabled = true;// to enable linkbutton.
lnk2.Enabled = false;// to disable linkbutton.
If You want to do it using rowindex, then you can e.Row.RowIndex to find the current row index inside 'RowDatabound` event of gridview. as:
if(e.Row.RowIndex==2)
{
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
lnk2.Enabled=false;
}
If you want to enable/ disable Linkbutton based on value of some other column in the same row, then you can do the same inside Rowdatabound event. as:
string Namecolumnvalue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
if(Namecolumnvalue =="Disable")
{
lnk2.Enabled=false;
}
else{
lnk2.Enabled=true;
}
--------aspx page code---------
<asp:GridView ID="gvLibrary" runat="server" AutoGenerateColumns="False" Width="100%" DataKeyNames="LibMstRefNo"
EmptyDataText="No Client Found" CssClass="table table-striped table-bordered" OnRowDataBound="gvLibrary_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Issue">
<ItemTemplate>
<asp:LinkButton ID="lnkIssue" runat="server" Text="Issue" OnClick="lnkIssue_Click"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Receive">
<ItemTemplate>
<asp:LinkButton ID="lnkReceive" runat="server" Text="Receive" OnClick="lnkReceive_Click" OnClientClick="return confirm('Are you Sure?')"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
------------aspx.cs page code------------------
protected void gvLibrary_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string nbps = e.Row.Cells[8].Text;
if(nbps== " ")
{
nbps = "";
}
else
{
nbps = e.Row.Cells[8].Text;
}
if (nbps == "")
{
LinkButton btn = (LinkButton)e.Row.FindControl("lnkissue");
LinkButton btn1 = (LinkButton)e.Row.FindControl("lnkReceive");
btn.Enabled = true;
btn1.Enabled = false;
btn1.ForeColor = System.Drawing.Color.Red;
}
else
{
LinkButton btn = (LinkButton)e.Row.FindControl("lnkissue");
LinkButton btn1 = (LinkButton)e.Row.FindControl("lnkReceive");
btn.Enabled = false;
btn.ForeColor = System.Drawing.Color.Red;
btn1.Enabled = true;
}
}
}
Why can't i change the value in a specific row in the rowdatabound event of my gridview? the code is entering where the value is set to Test but still shows old value?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="au_id" DataSourceID="SqlDataSource1"
ondatabinding="GridView1_DataBinding" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="au_id" HeaderText="au_id" ReadOnly="True"
SortExpression="au_id" />
<asp:BoundField DataField="au_lname" HeaderText="au_lname"
SortExpression="au_lname" />
<asp:BoundField DataField="au_fname" HeaderText="au_fname"
SortExpression="au_fname" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname] FROM [authors]">
</asp:SqlDataSource>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
var customerName = row.Field<String>("au_lname");
if (customerName == "Carson")
{
customerName = "Test";
}
}
}
Because you cannot change the underlying DataSource in RowDataBound(too late). You need to apply your changes to the TemplateFields controls or to the CellCollection of the row(in case of BoundFields or AutogenerateColumns=true):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
var customerName = row.Field<String>("au_lname");
if (customerName == "Carson")
{
e.Row.Cells[1].Text = "Test";
}else
{
e.Row.Cells[1].Text = customerName;
}
}
}