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;
}
Related
I'm working in Visual Studio 2015.
When the Gridview loads, I can click on "Edit".
When I click Cancel I'm just getting back to the Gridview.
So that good, but if I click "Update" he is doing the same thing as what is happening at "Cancel". No errors.
Here is the method for the OnRowUpdating :
protected void UpdateHandleiding(object sender, GridViewUpdateEventArgs e)
{
SqlConnection Sqlconnection1 = new SqlConnection();
Sqlconnection1.ConnectionString = (System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//string ID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblID")).Text;
//string Naam = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtNaam")).Text;
//string URL = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtURL")).Text;
GridViewRow row = GridView1.Rows[e.RowIndex];
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Naam = (row.Cells[1].Controls[0] as TextBox).Text;
string URL = (row.Cells[2].Controls[0] as TextBox).Text;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Handleidingen SET Naam=#Naam, URL=#URL WHERE ID=#ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Naam", Naam);
cmd.Parameters.AddWithValue("#URL", URL);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
GridView1.DataBind();
}
Here is my OnRowEditing & OnRowCancelingEdit which do work :
protected void EditHandleiding(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
ShowHandleidingen();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
ShowHandleidingen();
}
Here is my Gridview :
<asp:GridView ID="GridView1" runat="server" CssClass="grid-center" AutoGenerateColumns="False"
DataKeyNames="ID" EnableModelValidation="True" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="EditHandleiding" OnRowUpdating="UpdateHandleiding" OnRowCancelingEdit="CancelEdit">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Naam" HeaderText="Naam"/>
<asp:BoundField DataField="URL" HeaderText="URL"/>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
this is simple situation caused by the post back events in asp.net, in the Update Method the page is reloaded from the begining, even if you give new values to the data that you want too submit in the database, asp.net will take the one in the page_load method, when you fill the database in the first place at the page_load method add this condition :
private void Page_Load()
{
if (!IsPostBack)
{
// Fill up the gridView with the data that you want
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
}
replace object sender, GridViewUpdateEventArgs e
to
object sender, GridViewRowEventArgs e
Simply change gridview in aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
and then put
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{}
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
I'm having trouble with setting a HiddenField's value to a GridView item value. What I want to do is get the value of a BoundField (in this case, "FIPSCountyCode") in a GridView and store it in a HiddenField when the user clicks a button (in this case, "btnEdit") to make changes to a entry in the grid. I haven't used HiddenFields before, so I have forgotten what to do here.
The HiddenField is setup like this:
<asp:HiddenField ID="hdnFIPS" Value='<%#Eval("FIPSCountyCode")%>' runat="server" />
This is what the GridView is setup like:
<asp:GridView ID="CountyList" runat="server" AutoGenerateColumns="False" Width="90%" SkinId="PagedList" PagerSettings-Position="TopAndBottom" PagerStyle-Wrap="True">
<Columns>
<asp:BoundField HeaderText="County Code" DataField="FIPSCountyCode" />
<asp:BoundField HeaderText="State Code" DataField="StateCode" />
<asp:BoundField HeaderText="County Name" DataField="CountyName" />
<asp:BoundField HeaderText="Tax Rate" DataField="TaxRate" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" SkinID="EditIcon" OnClick="EditInfo" CommandName="DoEdit" />
<asp:ImageButton ID="DeleteButton" runat="server" SkinID="DeleteIcon" CommandName="DoDelete"
OnClientClick="return confirm('Are you sure you want to remove this item and all of its options?')"
CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle CssClass="even" />
</asp:GridView>
And this is the code behind:
public partial class Admin_County_Info : CommerceBuilder.UI.AbleCommerceAdminPage
{
private string redirectString = String.Empty;
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
PopulateCountyGrid();
}
protected void PopulateCountyGrid()
{
try
{
System.Data.SqlClient.SqlDataReader dr = null;
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT [FIPSCountyCode], [StateCode], [CountyName], [TaxRate] FROM [baird_InfoCounty]", cn);
cmd.CommandType = CommandType.Text;
cn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
CountyList.DataSource = dr;
CountyList.DataBind();
}
}
catch (Exception eX)
{
}
}
#region Clicks and Event Handlers
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}
protected void AddInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("~/Admin/Taxes/AddEditCountyInfo.aspx");
}
}
}
This must be a really dumb question but I'm really not sure how to proceed. Any help would be great!
You can get the value of FIPSCountyCode from the BoundField this way:
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
GridViewRow gvr = ((ImageButton)sender).NamingContainer as GridViewRow;
hdnFIPS.Value = gvr.Cells[0].Text;
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}
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;
}
}
}
I'm not able to bind my dropdownlist present in edititem template . I am getting null reference when i try to access it.
My design:
<asp:TemplateField HeaderText ="Category">
<ItemTemplate >
<asp:Label ID="drpcategory" Text ='<%#Bind("category") %>' runat ="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpcategory1" AppendDataBoundItems="True" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
My code behind:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_table1.EditIndex = e.NewEditIndex;
DropDownList drpcategory1 = ((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1"));
//BindDropDown(drpcategory1);
dt = con.GetData("Select category_name from category");
String str = gv_table1.Rows[e.NewEditIndex].FindControl("drpcategory1").GetType().ToString();
//((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1")).DataSource = dt;
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
this.setgrid();
}
I've tried looking on the net and tried many things in vain. I am new to asp. Thanks in advance. I would like the dropdown to be bound only when user enters edit mode.
Code Behind: Tested Code and also set dropdown-list selected value on edit mode
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("drpcategory1");
//bind dropdown-list
DataTable dt = con.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "category_name";
ddList.DataValueField = "category_name";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = dr["category_name"].ToString();
}
}
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
gridviewBind();// your gridview binding function
}
I do it like this. In which, Name and Id are two fields of Company object:
HTML Code:
<asp:TemplateField HeaderText="Công ty">
<EditItemTemplate>
<asp:DropDownList ID="ddlCompanyEdit" DataSource="<%# PopulateddlCompanyEdit() %>" DataValueField="Id" DataTextField="Name" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbCompany" runat="server" Text='<%#Bind("Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C# code behind:
protected IEnumerable<Company> PopulateddlCompanyEdit()
{
using (var bkDb = new BrickKilnDb())
{
return bkDb.Companies.ToList();
}
}
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
string Active = "";
if (e.Row.DataItem != null)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblEditActive = (Label)e.Row.FindControl("lblUP_ET_ActiveStatus");
if (lblEditActive.Text != string.Empty)
{
Active = lblEditActive.Text.Trim();
}
DropDownList ddlActive = (DropDownList)e.Row.FindControl("ddlUP_ET_ActiveStatus");
ddlActive.Items.Clear();
ddlActive.Items.Add("True");
ddlActive.Items.Add("False");
ddlActive.DataBind();
ddlActive.Items.FindByText(Active).Selected = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The event RowEditing occurs just before a row is edited.
You should use the RowDataBound event instead.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gv.EditIndex == e.Row.RowIndex &&
e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
//bind the control
}
}
You have to use RowDataBound event to bind the dropdown control for edited row. Please use below method in RowDataBound event.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
DataTable dt = con.GetData("Select category_name from category");
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
}
}
Hope this will help you.