My problem is,when i click edit,textbox appears in all columns and i write ehatever i want to update,then i click on update button,the rows gets updated in the database,but on page it shows previous values.Please help
<Columns>
<asp:TemplateField HeaderText="Email ID">
<ItemTemplate>
<asp:Label ID="Label1" ReadOnly="true" runat="server" Text='<%#Eval("EmailID")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("EmailID")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%#Eval("LastName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%#Eval("Password")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%#Eval("Password")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CurrentLocation">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%#Eval("CurrentLocation")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%#Eval("CurrentLocation")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile No.">
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%#Eval("MobileNo")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%#Eval("MobileNo")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%#Eval("Address")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" Text='<%#Eval("Address")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%#Eval("Gender")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox8" runat="server" Text='<%#Eval("Gender")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit" ShowEditButton="true"/>
code behind-
protected void GridView1_Edit(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox ac = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
TextBox a = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
TextBox b = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3");
TextBox c = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4");
TextBox d = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox5");
TextBox k = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox6");
TextBox f = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox7");
TextBox g = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox8");
ru.EmailID1=ac.Text;
ru.FirstName1=a.Text;
ru.LastName1=b.Text;
ru.Password1=c.Text;
ru.Location=d.Text;
ru.MobileNo=k.Text;
ru.Address=f.Text;
ru.gender = g.Text;
You can set the EnableViewState property to True for each TextBox in your gridview. This will ensure that the values you entered in Edit mode are seen after page posts back. Also, you may change Eval to Bind, as Eval is read-only while Bind works both ways.
I believe your problem is that you are not updating the DataSource of the GridView, thus when you call DataBind() on the grid, it is using the data it has in the non-updated data source, thus the "old" values appear.
Instead, once you have successfully saved the changes to the database, then perform the logic of querying the database to build the data source and then re-bind the grid, like this:
SaveChangesToDatabase();
GridView1.DataSource = GetDataFromDatabase();
GridView1.DataBind();
you can use the Response.Redirect and insert it after your code.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox ac = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
TextBox a = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
TextBox b = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3");
TextBox c = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4");
TextBox d = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox5");
TextBox k = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox6");
TextBox f = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox7");
TextBox g = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox8");
ru.EmailID1=ac.Text;
ru.FirstName1=a.Text;
ru.LastName1=b.Text;
ru.Password1=c.Text;
ru.Location=d.Text;
ru.MobileNo=k.Text;
ru.Address=f.Text;
ru.gender = g.Text;
Response.Redirect("currentpage.aspx" + "?urlparam1=" + value1 + "&urlparam2=" + value2);
Try it:
protected void GridViewUser_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
var id = e.NewValues["Id"] + string.Empty;
var login = e.NewValues["Login"] + string.Empty;
var password = e.NewValues["Password"] + string.Empty;
Validate(false,login, password);
var dto = new UserDto();
dto.Id = Convert.ToInt32(id);
dto.Login = (login + string.Empty).Trim();
dto.Password = password;
_userBo.Save(dto);
GridViewUser.EditIndex = -1;
}
catch (Exception ex)
{
Core.Util.Util.ShowPopUpMsg(this, "Erro não esperado: " + ex.Message);
}
finally
{
FillGrid();
}
}
Related
I have a simple problem with my gridview. It is an editable gridview which allows inserting, updating and deleting rows. It is bound to a datatable. I store the datatable in the viewstate and bind the datatable on page_load for every postback. There is no column order or paging and I only have a few records on this gridview. When there is no data to display, I add an empty message text like "no data found" manually to grid. It is okey for the first page_load. But after postback, this text disappears, but the row is still there. And the main problem is the row has "edit" and "delete" command columns after postback. This row should not have edit or delete columns after postback. It works really fine before postback.
This problem never happens if there is at least one row in gridview.
If I have at least one row, then if I add more rows: No problem
If I have the empty grid, then I add a row (before any postback for example combobox value change): No problem
If I have the empty grid: then I do a postback by changing a value in a combobox, then "no rows found" message in the grid disappearing and there is an extra row in the grid which has no text and has edit and delete columns
If I have the grid with that unwanted row, then I add a row to that gridview: The unwanted row is going away and new row appearing on the grid. No problem
So the only problem is that extra row which is appearing after postback.
Code details are below. Please help me with this silly problem. I couldnt solve it for days.
ASPX:
<asp:GridView ID="grdTerminals" runat="server"
AutoGenerateColumns="False" DataKeyNames="TRM_ID"
OnRowCancelingEdit="grdTerminals_RowCancelingEdit"
OnRowDataBound="grdTerminals_RowDataBound"
OnRowEditing="grdTerminals_RowEditing"
OnRowUpdating="grdTerminals_RowUpdating" ShowFooter="True"
OnRowCommand="grdTerminals_RowCommand"
OnRowDeleting="grdTerminals_RowDeleting"
HeaderStyle-BackColor="#73be1e" HeaderStyle-ForeColor="Window" HeaderStyle-Font-Bold="true" Width="500px" HeaderStyle-Height="30">
<Columns>
<asp:TemplateField HeaderText="Terminal" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="ddlTerminal" runat="server" DataTextField="TRM_MNMC" DataValueField="TRM_ID">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTerminal" runat="server" Text='<%# Eval("TRM_MNMC") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlNewTerminal" runat="server" DataTextField="TRM_MNMC" DataValueField="TRM_ID">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TAS No" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtTASNo" runat="server" Text='<%# Bind("TAS_NO") %>' Width="120"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewTASNo" runat="server" Width="120"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblTASNo" runat="server" Text='<%# Bind("TAS_NO") %>' Width="120"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Kaydet"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" CommandName="Insert" Text="Insert"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="" ShowDeleteButton="True" ShowHeader="True" DeleteText="Delete"/>
</Columns>
</asp:GridView>
C#
// I am storing the data in ViewState
DataTable dtTerminals
{
get
{
return ViewState["_dtVehicleTerminals"] as DataTable;
}
set
{
ViewState["_dtVehicleTerminals"] = value;
}
}
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (dtTerminals == null)
{
dtTerminals = new DataTable();
dtTerminals.Columns.Add("TRM_ID");
dtTerminals.Columns.Add("TRM_MNMC");
dtTerminals.Columns.Add("TAS_NO");
}
if (!IsPostBack)
{
string VhcId = Request["vhc_id"];//Edit mode
if (!string.IsNullOrEmpty(VhcId))
{
BindTerminalInfo(VhcId);
}
else
{
//To show empty grid
BindTerminalGrid();
}
}
// Bind Terminal Info
void BindTerminalInfo(string VhcId)
{
dtTerminals = VehicleManager.GetVehicleTerminals(VhcId);
BindTerminalGrid();
}
//Bind Terminal Grid
public void BindTerminalGrid()
{
if (dtTerminals.Rows.Count > 0)
{
grdTerminals.DataSource = dtTerminals;
grdTerminals.DataBind();
}
else
{
//Show No Records Found
dtTerminals.Rows.Add(dtTerminals.NewRow());
grdTerminals.DataSource = dtTerminals;
grdTerminals.DataBind();
grdTerminals.Rows[0].Cells.Clear();
grdTerminals.Rows[0].Cells.Add(new TableCell());
grdTerminals.Rows[0].Cells[0].Text = "No Data found";
dtTerminals.Rows.Clear();
}
}
//Other methods related to grid functionality
protected void grdTerminals_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlTerminal = (DropDownList)e.Row.FindControl("ddlTerminal");
if (ddlTerminal != null)
{
ddlTerminal.DataSource = VehicleManager.GetDefaultUserTerminalNames();
ddlTerminal.DataBind();
ddlTerminal.DataTextField = "TRM_MNMC";
ddlTerminal.DataValueField = "TRM_ID";
ddlTerminal.SelectedValue = grdTerminals.DataKeys[e.Row.RowIndex].Values[0].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlNewTerminal = (DropDownList)e.Row.FindControl("ddlNewTerminal");
ddlNewTerminal.DataSource = VehicleManager.GetDefaultUserTerminalNames();
ddlNewTerminal.DataBind();
}
}
protected void grdTerminals_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdTerminals.EditIndex = -1;
BindTerminalGrid();
}
protected void grdTerminals_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblId = (Label)grdTerminals.Rows[e.RowIndex].FindControl("lblTrmUnqId");
DropDownList ddlTerminal = (DropDownList)grdTerminals.Rows[e.RowIndex].FindControl("ddlTerminal");
TextBox txtTASNo = (TextBox)grdTerminals.Rows[e.RowIndex].FindControl("txtTASNo");
dtTerminals.Rows[e.RowIndex]["TRM_ID"] = ddlTerminal.SelectedValue;
dtTerminals.Rows[e.RowIndex]["TRM_MNMC"] = ddlTerminal.SelectedItem;
dtTerminals.Rows[e.RowIndex]["TAS_NO"] = txtTASNo.Text;
grdTerminals.EditIndex = -1;
BindTerminalGrid();
}
protected void grdTerminals_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string TrmId = Convert.ToString(grdTerminals.DataKeys[e.RowIndex].Values[0]);
dtTerminals.Rows.Remove(dtTerminals.Rows[e.RowIndex]);
BindTerminalGrid();
}
protected void grdTerminals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
DropDownList ddlNewTerminal = (DropDownList)grdTerminals.FooterRow.FindControl("ddlNewTerminal");
TextBox txtTASNo = (TextBox)grdTerminals.FooterRow.FindControl("txtNewTASNo");
DataRow dr = dtTerminals.NewRow();
dr["TRM_ID"] = ddlNewTerminal.SelectedValue;
dr["TRM_MNMC"] = ddlNewTerminal.SelectedItem.Text;
dr["TAS_NO"] = txtTASNo.Text;
dtTerminals.Rows.Add(dr);
BindTerminalGrid();
}
}
protected void grdTerminals_RowEditing(object sender, GridViewEditEventArgs e)
{
grdTerminals.EditIndex = e.NewEditIndex;
BindTerminalGrid();
}
I am not sure it is the correct solution . But try adding Empty data text property of Gridview.
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
emptydatatext="No data in the data source."
runat="server">
<emptydatarowstyle backcolor="LightBlue"
forecolor="Red"/>
</asp:gridview>
Or try like this
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgBtnUpdate" runat="server" Height="32px"
ImageUrl="~/Images/Update.jpg" ToolTip="Update" Width="32px" CommandName="Update"/>
<asp:ImageButton ID="imgBtnDelete" runat="server" Height="32px"
ImageUrl="~/Images/delete.gif" style="margin-left: 0px" ToolTip="Delete"
Width="32px" CommandName="Delete"/>
<asp:ImageButton ID="imgBtnCancel" runat="server" Height="32px"
ImageUrl="~/Images/Cancel.png" ToolTip="Cancel" Width="32px" CommandName="Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/AddNew.gif"
ToolTip="Add New Record" CommandName="Add"/>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" Height="32px"
ImageUrl="~/Images/pencil.png" ToolTip="Edit" Width="32px" CommandName="Edit"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNameFooter" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
Finally I have fixed this problem. The solution is adding
if (!Request.Form["__EVENTTARGET"].Split('$').Contains(grdTerminals.ID))
{
BindTerminalGrid();
}
code block to If(Postback) statement. I should rebind data for everypostback but only if the control which caused postback is not the "datagrid".
protected void gv_examiner_list_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string n = (string)DataBinder.Eval(e.Row.DataItem, "id_examiner"); //this can return value from Label
string n_2 = e.Row.Cells[0].Text; //this return ""
}
}
i'm sure that cell[0] have value in gridview, but return ""
this is my gridview, i tried to get value on RowDataBound to plus in SQL query. After query ,then return datatable to bind to DropDownList whose id is "ddl_gv_examiner_list_n_building"
<asp:GridView ID="gv_examiner_list" runat="server" AutoGenerateColumns="False"
OnRowDataBound="gv_examiner_list_OnRowDataBound"
OnRowEditing="gv_examiner_list_OnRowEdition"
OnRowCancelingEdit="gv_examiner_list_OnRowCancelingEdit"
OnRowUpdating="gv_examiner_list_OnRowUpdating">
<Columns>
<asp:TemplateField HeaderText="รหัสผู้สอบ">
<ItemTemplate>
<asp:Label ID="lb_gv_examiner_list_id_examiner" runat="server" Text='<%# Eval("id_examiner")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ชื่อ">
<ItemTemplate>
<asp:Label ID="lb_gv_examiner_list_fname" runat="server" Text='<%# Eval("fname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="นามสกุล">
<ItemTemplate>
<asp:Label ID="lb_gv_examiner_list_lname" runat="server" Text='<%# Eval("lname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="อาคาร">
<ItemTemplate>
<asp:Label ID="lb_gv_examiner_list_n_building" runat="server" Text='<%# Eval("n_building")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_gv_examiner_list_n_building" runat="server"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ชั้น">
<ItemTemplate>
<asp:Label ID="lb_gv_room_provided_floor" runat="server" Text='<%# Eval("floor") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ชื่อห้อง">
<ItemTemplate>
<asp:Label ID="lb_gv_room_provided_n_exam_room" runat="server" Text='<%# Eval("n_exam_room")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="เลขที่นั่งสอบ">
<ItemTemplate>
<asp:Label ID="lb_gv_room_provided_seat_number" runat="server" Text='<%# Eval("seat_number")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
In the Row you need to find Label instead of cell text, then you can find the text in label. You should do like below:
protected void gv_examiner_list_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string n = string.Empty;
string n2 = string.Empty;
Label lblId = e,Row.FindControl("lb_gv_examiner_list_id_examiner") as Label;
Label lblFirstName = e,Row.FindControl("lb_gv_examiner_list_fname") as Label;
if (lblId != null && lblFirstName != null)
{
n= lblId.Text;
n2 = lblFirstName.Text;
}
}
}
Hope it helps!
I have a Gridview:
<asp:GridView ID="gvtransaction" runat="server" AutoGenerateColumns="False" Width="60%" OnRowDataBound="gvtransaction_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Bind("id") %>' Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Consumer">
<ItemTemplate>
<asp:Label ID="lblfirstname" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbllastname" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='<%# Bind("Amount") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="lblcurrencyID" runat="server" Text='<%# Bind("CurrencyID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Account Name">
<ItemTemplate>
<asp:Label ID="lblcurrencyname" runat="server" Text='<%# Bind("CurrencyName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblstatus" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DateCreated">
<ItemTemplate>
<asp:Label ID="lbldatecreated" runat="server" Text='<%# Bind("DateCreated") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="btnApprove" runat="server" Text="Approve" OnClick="btnApprove_Click"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="btnReject" runat="server" Text="Reject" OnClick="btnReject_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is the code for the onclick = "btnApprove_click():
GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
string id = ((Label)row.FindControl("lblid")).Text;
Response.Write(row.RowIndex);
string ApprovedStatus = "Approved";
Button btnApprove = (Button)sender;
btnApprove.Enabled = false;
string status = ClassBiller.ConsumerAcceptedStatus(int.Parse(id), ApprovedStatus, DateTime.Now);
ViewPendingConsumer(); //rebind gridview para magEffect yun update
my concern is, how can i disable the buttons inside my gridview when i clicked either the Approve Button or the Reject Button.
sample scenario:
when I click Approve, the buttons should be disabled so that the it will prevent the user to click the button again..
I have read some articles which suggests the use of gridview's onrowdatabound..But i am confuse on how to do it...
I tried using
row.Enabled = false;
still doesnt work...
help please..
thank you
You can try to disable the button inside its click event. But when your gridview databinds again, the button will be enabled back..
protected void btnApprove_Click(object sender, EventArgs e)
{
Button btnApprove = (Button)sender;
btnApprove.Enabled = false;
}
Try to use rowdatabound event of Grid View, Firstly Find the control by using FindControl method like
protected void gvtransaction_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// For `Approve` button
Button btnapprove = (Button)e.Row.FindControl("btnApprove"); // give property id of button form template field
btnapprove.Enabled = true; //true means enable else you may set false to disable button
// For `Reject` button
// Same condition but in `FindControl` method use `btnReject` id.
}
}
That's for Approve button For Reject button you may use same logic.
Link For Help
Hope it clear and works for you.
This is all you need to do, where Cells[5] is the cell where you have your Button, had the same problem and it worked for me.
protected void gvtransaction_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[5].Enabled = false;
}
}
I am having issue when updating gridview! everything is seems to be working. but when i hit finish editing the data will not save!
but when i click edit the correct fields prompt me to enter new value but it wont save!
here is my asp
<asp:GridView ID="GridView1" runat="server" CssClass="report"
AutoGenerateColumns="False" onrowediting="GridView1_RowEditing"
DataKeyNames="TimeID" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand"
onrowcancelingedit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="date" Visible="true" ReadOnly="true" HeaderText="Date" />
<asp:BoundField DataField="Description" HeaderText="Stage Description" ReadOnly="True" />
<asp:TemplateField HeaderText="Start Time">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStartTime" ValidationGroup="1" Width="90px" class="TimeEntry" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtStartTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Time">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEndTime" class="TimeEntry" ValidationGroup="1" Width="90px" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator66" ControlToValidate="txtEndTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TimeInHours" HeaderText="Time Time (Hours)" ReadOnly="True" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true"
ButtonType="Image" EditImageUrl="~/images/edit_record.jpg"
CancelImageUrl="~/images/edit_no.jpg"
UpdateImageUrl="~/images/update_record.jpg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="lnbCopy" runat="server" AlternateText="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Bind("TimeID") %>' OnClientClick="return confirm('Are you sure you want to delete this row?');" ImageUrl="~/images/delete_record.jpg" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTimeID" runat="server" Text='<%# Eval("TimeID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is what i have done in behind code
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
loadTable();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
loadTable();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
var StartTime = row.FindControl("txtStartTime") as TextBox;
var EndTime = row.FindControl("txtEndTime") as TextBox;
var id = row.FindControl("lblTimeID") as Label;
SqlConnection conn = new SqlConnection(conStr.GetConnectionString("myServer1"));
SqlCommand comm = new SqlCommand();
comm.CommandText = "UPDATE CDSTimeSheet SET StartTime = #StartTime, EndTime = #EndTime ,timeElapsed = datediff(minute,#startTime , #EndTime), timeInSeconds = datediff(second,#startTime , #EndTime) WHERE TimeID = #id";
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", id.Text);
comm.Parameters.AddWithValue("#StartTime", StartTime.Text);
comm.Parameters.AddWithValue("#EndTime", EndTime.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
loadTable();
}
what am i doing wrong?
It sounds a lot like you are not calling DataBind on your grid after updating the underlying data. After you perform the update (possibly within the loadTable method that I see referenced up there), call
GridView1.DataBind();
That should refresh the data in the grid.
After your comments, I see that you're not using the NewValues collection in the GridViewUpdateEventArgs parameter to get the actual incoming, updated field values. Try this:
String StartTime = e.NewValues["StartTime"].ToString();
String EndTime = e.NewValues["EndTime"].ToString();
String id = e.Keys[0].ToString();
Note that these variables are strings now, not TextBoxs, so you don't need to add ".Text" on them when you add them as parameters.
Handle the postback, basically if you fill the grid view in each postback you are re filling the gridview with old data, that's why you retrieve data with no changes (remember after Update button this trigger a postback). So, in case this is your case, try this.
if(!this.IsPostback)
{
(Method that fills your GridView)
}
I have used below code for GridViewRowUpdating, but after click on update button, it takes old values.
I checked by break point for GridViewRowIpdating, and all the text boxes have old values. And new entered values do not grab.
I tried a lot in google but I could not solve the problem.
protected void GridViewDocuments_Search_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
_DataContext = new EDMSDataContext();
int _Docid = (int)GridViewDocuments_Search.DataKeys[e.RowIndex].Value;
TextBox DocumentNo = (TextBox)GridViewDocuments_Search.Rows[e.RowIndex].FindControl("DocumentNo");
TextBox title = (TextBox)GridViewDocuments_Search.Rows[e.RowIndex].FindControl("title");
TextBox unit = (TextBox)GridViewDocuments_Search.Rows[e.RowIndex].FindControl("unit");
TextBox originator = (TextBox)GridViewDocuments_Search.Rows[e.RowIndex].FindControl("originator");
_DataContext.updateDoc(_Docid, DocumentNo.Text, title.Text, unit.Text, originator.Text);
_DataContext.SubmitChanges();
GridViewDocuments_Search.EditIndex = -1;
var query = _DataContext.spQuickSearchDoc(txtSearchKeywords.Text);
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
}
protected void GridViewDocuments_Search_RowEditing(object sender, GridViewEditEventArgs e)
{
//var query = _DataContext.spQuickSearchDoc(txtSearchKeywords.Text);
// GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.EditIndex = e.NewEditIndex;
GridViewDocuments_Search.DataBind();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var query = _DataContext.spQuickSearchDoc(txtSearchKeywords.Text);
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
}
Grid view marks up:
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False
Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand" OnRowDeleting="GridViewDocuments_Search_RowDeleting"
DataKeyNames="DocID" PageSize="100"
onrowcancelingedit="GridViewDocuments_Search_RowCancelingEdit"
onrowediting="GridViewDocuments_Search_RowEditing"
onrowupdating="GridViewDocuments_Search_RowUpdating" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DocNo">
<EditItemTemplate>
<asp:TextBox ID="DocumentNo" runat="server" Text='<%# Eval("DocumentNo") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("DocumentNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="title">
<EditItemTemplate>
<asp:TextBox ID="title" runat="server" Text='<%# Eval("title") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DocID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("DocID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("DocID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Originator">
<EditItemTemplate>
<asp:TextBox ID="Originator" runat="server" Text='<%# Eval("Originator") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Originator") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit">
<EditItemTemplate>
<asp:TextBox ID="Unit" runat="server" Text='<%# Eval("Unit") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("Unit") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
GridViewDocuments_Search_RowCommand
protected void GridViewDocuments_Search_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowindex = Convert.ToInt32(e.CommandArgument.ToString());
_DataContext = new EDMSDataContext();
int _Docid = (int)GridViewDocuments_Search.DataKeys[rowindex].Value;
switch (e.CommandName)
{
case "Details":
Response.Redirect("~/Documentfortest.aspx?DocID=" + _Docid);
break;
case "Delete":
_DataContext.DeleteDoc(_Docid);
_DataContext.SubmitChanges();
break;
}
var query = _DataContext.spQuickSearchDoc(txtSearchKeywords.Text);
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
//UpdatePanel1.Update();
}
I think you need to move your databind code in rowcommand under Case "Delete" before break;, you are rebinding your gridview in rowcommand for every command that is fired (edit/update).
For example:
protected void GridViewDocuments_Search_RowCommand
(object sender, GridViewCommandEventArgs e)
{
int rowindex = Convert.ToInt32(e.CommandArgument.ToString());
_DataContext = new EDMSDataContext();
int _Docid = (int)GridViewDocuments_Search.DataKeys[rowindex].Value;
switch (e.CommandName)
{
case "Details":
Response.Redirect("~/Documentfortest.aspx?DocID=" + _Docid);
break;
case "Delete":
_DataContext.DeleteDoc(_Docid);
_DataContext.SubmitChanges();
//rebind only if row is deleted
var query = _DataContext.spQuickSearchDoc(txtSearchKeywords.Text);
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
break;
}
}
The RowUpdating event fires before your data in updated in the grid. This allows you to make any changes to the data before it is updated.
The newly entered values are available to you in the collection NewValues.
This is how you could use it.
protected void GridViewDocuments_Search_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
_DataContext = new EDMSDataContext();
int _Docid = (int)GridViewDocuments_Search.DataKeys[e.RowIndex].Value;
_DataContext.updateDoc(_Docid,
e.NewValues["DocumentNo"].ToString(),
e.NewValues["title"].ToString(),
e.NewValues["unit"].ToString(),
e.NewValues["originator"].ToString());
_DataContext.SubmitChanges();
GridViewDocuments_Search.EditIndex = -1;
var query = _DataContext.spQuickSearchDoc(txtSearchKeywords.Text);
GridViewDocuments_Search.DataSource = query;
GridViewDocuments_Search.DataBind();
}
Note: There is also a RowUpdated event that fires after the row is updated.