Updating gridview row is not saving the data - asp.net

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)
}

Related

How can I update all the data in a database specified by selected rows in Asp GridView with a button located outside of the GridView?

I looked for some similar questions, but found only ListView solutions
But I have a GridView and a button outside of the GridView and need to udate only records specified by a selected checkbox.
<asp:GridView ID="gvData"
runat="server" Width = "850px"
CellPadding="5"
AutoGenerateColumns="false"
AllowPaging ="true"
OnPageIndexChanging ="OnPaging" PageSize="5">
<HeaderStyle CssClass="HeaderStyle" />
<PagerStyle CssClass="HeaderStyle" HorizontalAlign="Center" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<RowStyle CssClass="RowStyle" />
<RowStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="20px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Message" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblMessage" runat="server" Width="500px" Text='<%# Eval("Message") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="text-align:left;">
<asp:Button ID="btnChange" runat="server" Text="Change Type" OnClick="btnChange_Click" />
</div>
I have a method btnChange_Click():
protected void btnChange_Click()
{
int index = gvFailedMerchants.SelectedRow.RowIndex;
DbConnection.UpdateMessageType(index);
}
When I click the button, I'm getting the message
"Object reference not set to an instance of an object"
I want to write a logic that where I traverse the grid and add ids of the selected row into one string where all ids are separated by commas:
1,2,3,4,5
Then I will send this string to the stored procedure and use them in a query within IN close:
UPDATE MYTABLE SET column = myValue WHERE ID IN('1,2,3,4,5')
I do not know what is the right approach to the problem.
How can I do that?
Please try this,
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"
OnCheckedChanged="ChkSelect_CheckedChanged" data-id='<%# Eval("id") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
protected void ChkSelect_CheckedChanged(object sender, EventArgs e)
{
try
{
CheckBox chkSel = sender as CheckBox;
string id= chkSel.Attributes["data-id"].ToString();
if (chkSel.Checked == true)
{
Session["ID"] += (Session["ID"].ToString() == "" ? id: "," + id);
}
else
{
string existingCodes = Session["ID"].ToString();
Session["ID"] = existingCodes.Replace(id, "");
}
protected void btnChange_Click()
{
string ids = Session["ID"].ToString();
DbConnection.UpdateMessageType(ids);
}

asp.net editable gridview "no data found" row causes issue after postback

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".

gridview asp.net c# onrowupdating

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();
}
}

Click "Accept" button in Gridview then move the record in another Gridview in different page

I want a gridview that having "ACCEPT" button then after clicking it. I want the accepted record to be moved or transferred in another gridview which is located in another page?
I already have two gridviews:
Gridview1 named PendingRecordsGridview.
Gridview2 named AcceptedRecordsGridview.
I already made a register.aspx page that after clickng register button, It will send the data in PendingRecordsGridview. And It works! And now, Like i said. I want to add "ACCEPT" button in that gridview, so after clicking the accept button. The record will be transfer to AcceptedRecordsGridview (another page) please! Help!
Refer this.. i have tested it..
things you have to keep in mind..
you have to create two different tables for your two gridview.. but those table design should be same of tbl1 and tbl2.. in tbl1 make one field as primarykey and make it auto-incremented
don't keep any primarykey or and auto-incremented field in tbl2
here on accept button first data will be inserted in to tbl2 and then delete from original table tbl1
page.aspx file
<asp:GridView ID="PendingRecordsGridview" runat="server"
AutoGenerateColumns="False" DataKeyNames="id"
onrowcommand="PendingRecordsGridview_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Accept">
<ItemTemplate>
<asp:Button CommandArgument='<%# Bind("id") %>' ID="Button1" runat="server" CausesValidation="false"
CommandName="accept" Text="Accept" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="name" SortExpression="name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id" SortExpression="id">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sd1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [tbl1]"></asp:SqlDataSource>
now page.aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void bind()
{
PendingRecordsGridview.DataSource = sd1;
PendingRecordsGridview.DataBind();
}
protected void PendingRecordsGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "accept")
{
Session["id"] = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO tbl2 (id, name) SELECT id, name FROM tbl1 where id='"+Session["id"].ToString()+"'", con);
SqlCommand cmd2 = new SqlCommand("delete from tbl1 where id='"+Session["id"].ToString()+"'", con);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
bind();
}
}
now just take another page.. and bind it with tbl2 which will be having records which are approved...
feel free to ask regarding this.. and mark it as answer if u found it helpful

Get Gridview dropdownList value

work on asp.net vs05.I have a grid
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
DataKeyNames="StudentID" OnSelectedIndexChanged="GridView3_SelectedIndexChanged"
OnRowDataBound="GridView3_RowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="StudentID" ReadOnly="True"
SortExpression="StudentID" />
<asp:BoundField DataField="StudentName" HeaderText="StudentName" />
<asp:TemplateField HeaderText="DivisionName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("StudentName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
Width="160px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Select" HeaderText="Update"
Text="Update" />
</Columns>
</asp:GridView>
Using The button Click i want to save value on database.But i can not read value from the dropdownlist
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
String Dis =
((DropDownList)sender).FindControl("DropDownList1").ToString();
//**want to get this value**
}
How can i get ddl selected value?i want to put the object of a class on ddl .Bellow code work on desktop ,Want same thing on web.
DropDownList1.DisplayMember = "CommercialRegionName";
foreach (class oItem in _collection)
{
DropDownList1.Items.Add(oItem);
//**want to save object,Not any object item like:oItem.Name.**
}
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
//PROBABLY YOU WANT TO GET ITEM FROM SELECTED ROW'S DROPDOWN
var ddl = (selectRow).FindControl("DropDownList1") as DropdownList;
if(dis!=null){
var s=ddl.SelectedItem.Text;
}
}

Resources