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;
}
}
}
Related
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;
}
The code was working before and all i did was add a new textbox in the header template of the gridview.
So What is my code doing:
i have an image button on my gridview view when clicked i take the value of of the current row of the gridview and the value of cell 3 and set it equal to my textbox. Then based on that value i am making two details view visible using a modal popup extender, one detail view renders correctly but will not function unless it gets the value from textbox10.text as a parameter, another details view will not even show the details because the select query takes the textbox10.text as a parameter.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (!IsPostBack)
{
}
else
{
ImageButton imgbtn = (ImageButton)sender;
GridViewRow GridView1 = (GridViewRow)imgbtn.NamingContainer;
string workordernum = GridView1.Cells[3].Text;
TextBox10.Text = workordernum;
//TextBox10.Text = "1";
ModalPopupExtender2.Show();
DetailsView2.Visible = true;
ModalPopupExtender1.Show();
DetailsView1.Visible = true;
}
}
when i put the above code in debug mode:
after debug completed:
When i set the textbox10.text = 1 and ran the application:
complete application with value 1:
.aspx code of the details view:
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="pnl2" PopupControlID="pnl2" BackgroundCssClass="modalBackground" DropShadow="False" X="30" Y="300" ValidateRequestMode="Inherit"></asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField2" runat="server" />
<asp:Panel ID="pnl2" runat="server" Width="881px" Height="175px" CssClass="pnl2BackGround" >
<asp:DetailsView ID="DetailsView2" runat="server" DataSourceID="SqlDataSource3" BackColor="#593B03" Height="175px" Width="881px" Font-Bold="True" ForeColor="White" PostBack = "False" AutoGenerateRows="False" DataKeyNames="WorkOrderNum" >
<Fields>
<asp:BoundField DataField="WorkOrderNum" HeaderText="WorkOrderNum" InsertVisible="False" ReadOnly="True" SortExpression="WorkOrderNum" />
<asp:BoundField DataField="Requestor" HeaderText="Requestor" SortExpression="Requestor" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" DataFormatString="{0:dd-M-yyyy}" />
<asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />
<asp:BoundField DataField="CompletionDate" HeaderText="CompletionDate" SortExpression="CompletionDate" DataFormatString="{0:dd-M-yyyy}" />
<asp:BoundField DataField="MachineDescription" HeaderText="MachineDescription" SortExpression="MachineDescription" />
<asp:BoundField DataField="MachineLocation" HeaderText="MachineLocation" SortExpression="MachineLocation" />
<asp:BoundField DataField="Type_of_Work_Order" HeaderText="Type_of_Work_Order" SortExpression="Type_of_Work_Order" />
<asp:BoundField DataField="Work_Required" HeaderText="Work_Required" SortExpression="Work_Required" />
</Fields>
</asp:DetailsView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:WorkOrderConnectionString6 %>" SelectCommand="SELECT [WorkOrderNum], [Requestor], [Date], [Department], [CompletionDate], [MachineDescription], [MachineLocation], [Type of Work Order] AS Type_of_Work_Order, [Work Required] AS Work_Required FROM [Master] WHERE ([WorkOrderNum] = #WorkOrderNum)">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox10" Name="WorkOrderNum" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
The Code i am using for the searching of the gridview from the header template:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Filter"] = "All";
DetailsView1.Visible = false;
TextBox10.Visible = false;
DetailsView2.Visible = false;
DetailsView3.Visible = false;
ReportViewer1.Visible = false;
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
String WorkOrderConnectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["WorkOrderConnectionString3"].ConnectionString;
SqlConnection con = new SqlConnection(WorkOrderConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("spx_GetWorkOrderNum");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Filter", ViewState["Filter"].ToString());
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
TextBox TextBox92 = (TextBox)GridView1.HeaderRow.FindControl("WorkOrderNum");
}
protected void TextBox92_TextChanged(object sender, EventArgs e)
{
TextBox TextBox92 = (TextBox)sender;
ViewState["Filter"] = TextBox92.Text;
this.BindGrid();
}
I am suspecting that post back might be the issue, some where in the code it is doing an unnessary post back so when i click the imagebutton it is not getting the value
Please help me find the error in my code as the debugger is not helping me and plus this was a working code before :(
WHY THE TEXTBOX VALUE = "" INSTEAD OF THE GRIDVIEW CELL VALUE??????
Thanks
Since Gridview is a Control and TextBox is also an Control within the Gridview control we nee to do this:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton imgbtn = (ImageButton)sender;
GridViewRow GridView1Row = (GridViewRow)imgbtn.NamingContainer;
Label FLabel = GridView1Row.Cells[2].Controls[0].FindControl("Label1") as Label;
string workordernum = FLabel.Text;// GridView1Row.Cells[3].Text;
TextBox10.Text = workordernum;
ModalPopupExtender2.Show();
DetailsView2.Visible = true;
ModalPopupExtender1.Show();
DetailsView1.Visible = true;
}
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;
}
}
}