Issue with updating rows in a gridview - c#

I have gridview where users can edit and update data in gridview but my issue is when i put some text in the Action field, nothing is updated. I have tried to run debug mode so i can watch what what is happening but i don't see the values i typed in the text box, it shows blank in my variable. Here is my aspx code:
<asp:GridView ID="GridView1" runat="server" Width = "855px" AutoGenerateColumns = "False" Font-Names = "Arial"
OnPageIndexChanging = "OnPaging" onrowediting="EditGridView1"
onrowupdating="UpdateGridView1" onrowcancelingedit="CancelEdit" CellPadding="3"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "ID">
<ItemTemplate>
<asp:Label ID="lblQST_SK" runat="server" Text='<%# Eval("QUEST_SK")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="10px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Action">
<ItemTemplate>
<asp:Label ID="lblAction" runat="server" Text='<%# Eval("ACTION")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAction" runat="server" Text='<%# Eval("ACTION")%>' TextMode="MultiLine" Height="80px"></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White"
HorizontalAlign="Left" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
</asp:GridView>
here is my code behind:
protected void UpdateGridView1(object sender, GridViewUpdateEventArgs e)
{
string QUEST_SK = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblQST_SK")).Text;
string ACTION = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAction")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update mytable set ACTION=#ACTION" +
"where QUEST_SK=#QUEST_SK;" +
"SELECT QUEST_SK, ACTION FROM mytable";
cmd.Parameters.Add("#QUEST_SK", SqlDbType.VarChar).Value = QUEST_SK;
cmd.Parameters.Add("#ACTION", SqlDbType.VarChar).Value = ACTION;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}

Try to write the function below in Page Load Event :
Page_Load()
{
if(IsPostBack)
{
return`;
}
}

Related

Reordering Columns in a Gridview Dynamically

I have a gridview I'm trying to reorder the columns for, but I'm getting an object not found error.
The code works when I don't include the code under "//code to move columns", but when I include that code, I get an object not found error that "s += txtAD.Text.Trim();" object reference is not set to an instance. It's weird because no matter which columns I switch, it always throws the error that it can't find column 1.
Any ideas?
My HTML:
<asp:GridView ID="gridviewtxSLds" ClientIDMode="Static" runat="server" CssClass="gridclassscrolledtx" CellPadding="0" ForeColor="#333333" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Metric">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("item") %>'
ID="txtctrltype" class="modalpopup2" AutoPostBack="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="AD">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("AD") %>'
ID="txtAD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="BD">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("BD") %>'
ID="txtBD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="CD">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Bind("CD") %>'
ID="txtCD" onfocus="blur()" class="txttime" AutoPostBack="false" ReadOnly="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
code in codebehind to fill gridview
using (var cmdtx2 = new SqlCommand(sqlcmd, conn))
{
DataTable dv = new DataTable();
SqlDataAdapter db = new SqlDataAdapter(cmdtx2);
//code to move columns
var columnMove = gridviewtxSLds.Columns[3];
gridviewtxSLds.Columns.RemoveAt(3);
gridviewtxSLds.Columns.Insert(2, columnMove);
db.Fill(dv);
gridviewtxSLds.DataSource = dv;
gridviewtxSLds.DataBind();
}
Update code, which throws the error:
protected void Bulk_Insert(object sender, EventArgs e)
{
var timeinitid = hfptstate.Value;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < gridviewtxSLds.Rows.Count; i++)
{
#region textbox declarations
TextBox txtitem = gridviewtxSLds.Rows[i].FindControl("txtctrltype") as TextBox;
TextBox txtAD = gridviewtxSLds.Rows[i].FindControl("txtAD") as TextBox;
TextBox txtBD = gridviewtxSLds.Rows[i].FindControl("txtBD") as TextBox;
TextBox txtCD = gridviewtxSLds.Rows[i].FindControl("txtCD") as TextBox;
#endregion textbox declarations
#region command string
string s = "update 1874tx set AD";
s += "='";
//following line throws the error
s += txtAD.Text.Trim();
s += "', ";
s += "BD";
s += "='";
s += txtBD.Text.Trim();
s += "', ";
s += "CD";
s += "='";
s += txtCD.Text.Trim();
s += "' where item";
s += "='";
s += txtitem.Text.Trim();
s += "';";
#endregion
sb.Append(s.ToString());
SqlCommand cmd = new SqlCommand(sb.ToString(), con);
con.Open();
cmd.ExecuteNonQuery();
}
}
Edit: And before anyone comments on concatenation of SQL queries, I know, and for this specific use it doesn't matter.

(Gridview)1st record is being deleted from database c#

<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Add Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" OnClick="btnadd_Click" CommandName="insert"
Text="Insert"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="True" OnClick="btndelete_Click" CommandName="delete"
Text="delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%#Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Bind("client_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%#Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Google Email">
<ItemTemplate>
<asp:Label ID="lblgemail" runat="server" Text='<%#Bind("google_email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Number">
<ItemTemplate>
<asp:Label ID="lblcont" runat="server" Text='<%#Bind("contact_number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="role">
<ItemTemplate>
<asp:Label ID="lblrole" runat="server" Text='<%#Bind("role") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
I have a table with 100 record
This is my Gridview I have two buttons add and delete(on Delete buttonClick particular record should be deleted from database) like, I clicked on record number 35(record number 35 should be deleted) but instead record number 1 is being deleted everytime.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
Label lblname = (Label)g.FindControl("lblname");
Button btnde = (Button)g.FindControl("btndelete");
//Response.Redirect("cs.aspx");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
}
protected void btndelete_Click(object sender, EventArgs e)
{
delete();
GridView1.Visible = false;
}
This is my CS code.
It's because on delete you are deleting record using foreach loop which is not a good way to do. You could try out this:
public void delete(string Name)
{
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + Name + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
And on Delete button click find the particular row and send it to delete Method
protected void btndelete_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
string name = ((Label)gvr.FindControl("lblname")).Text;
delete(name);
GridView1.Visible = false;
}
Note: Also you could write your redirection inside button click event on basis of delete method return.
You can find your Label control position and get their value, then delete from database. It will work fine.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
if(g.RowType == DataControlRowType.DataRow)
{
Label lblname = (Label)g.FindControl("lblname");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
break;
}
}
}

“Input string was not in a correct format” error

I have a code for Updating the Row in a gridview, but the issue is that, when I edit and update the Row it is giving me error as Input string was not in a correct format. At the below line of Code:-
cmd.Parameters.Add("#Active", SqlDbType.Int).Value = Convert.ToInt32(Active);
Please see my code for your reference:-
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;"
CellPadding="3" AutoGenerateColumns="False" AllowPaging="true" PageSize="4" CssClass="hoverTable"
OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowEditing="grdPostData_RowEditing"
OnRowDataBound="grdPostData_RowDataBound" DataKeyNames="Id" OnRowCommand="grdPostData_RowCommand" OnRowUpdating="grdPostData_RowUpdating">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td">
<ControlStyle CssClass="k-grid td"></ControlStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30"
ControlStyle-CssClass="k-grid td">
<ControlStyle CssClass="k-grid td"></ControlStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
</ItemTemplate>
<ItemStyle Width="50px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td">
<ControlStyle CssClass="k-grid td"></ControlStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" CommandName="eDelete" CommandArgument='<%# Bind("Id") %>' ImageUrl="~/images/delete.png"
runat="server" Width="15px" Height="15px" CausesValidation="False"
OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
<HeaderStyle Width="15%"></HeaderStyle>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" CausesValidation="false"
ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png"
UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
<ItemStyle Width="15px"></ItemStyle>
</asp:CommandField>
</Columns>
<EmptyDataTemplate>
No Result Found
</EmptyDataTemplate>
</asp:GridView>
Also see the CS code:-
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
string PostTitle = ((TextBox)(row.Cells[0].Controls[0])).Text;
string Postdesc = ((TextBox)(row.Cells[1].Controls[0])).Text;
// string ddlPostCategory = ((DropDownList)(row.Cells[2].Controls[0])).SelectedValue;
string Active = ((TextBox)(row.Cells[3].Controls[0])).Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = Id;
cmd.Parameters.Add("#title", SqlDbType.NVarChar, 155).Value = PostTitle;
cmd.Parameters.Add("#description", SqlDbType.NVarChar, 99999999).Value = Postdesc;
cmd.Parameters.Add("#Active", SqlDbType.Int).Value = Convert.ToInt32(Active);
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
//GET GDATA FROM DATABASE AND BIND TO GRID VIEW
}
}
I know this is not worth a question, tried but couldn't find. Please help.
Code for Dropdownlist aspx:-
<div class="controls">
<asp:DropDownList ID="ddlActiveInactive" CssClass="selectpicker form-control-drp wd"
runat="server" Style="width: 100%" ValidationGroup="AddNew">
<asp:ListItem Value="1" Text="Active"></asp:ListItem>
<asp:ListItem Value="0" Text="InActive"></asp:ListItem>
</asp:DropDownList>
</div>
It is a dropdownlist which has values Active and InActive
If you actually want to get the DropDownList's selected value use FindControl:
var ddlActive = (DropDownList)row.FindControl("ddlActiveInactive");
int active = -1; // or whatever
if(ddlActive.SelectedValue != "")
active = int.Parse(ddlActive.SelectedValue);
// ...
cmd.Parameters.Add("#Active", SqlDbType.Int)
.Value = active != -1 ? active : System.Data.SqlTypes.SqlInt32.Null;
Use trim() function to remove the whitespaces and the convert it to int.
cmd.Parameters.Add("#Active", SqlDbType.Int).Value = Convert.ToInt32(Active.Trim());

Selecting a Datevalue from GridView Cell and Use it as Parameter to a SQL Query

Hi I am Presently running an ASP.NET application
Now problem is with the Next button in the app, whenever someone clicks it, it returns the data of date range SYSDATE + 18 to SYDATE + 36 . But the way it should work is .. it should take the first date value from the GridView Date Cell and Returns the data for GridViewFirstCellDate+18 to GridViewFirstCellDate+36. My Gridview code is al follows. Eg the date in Image is Tuesday,November 19,2013 , so clicking Next button should retrun from 7/12/2013 and 25/12/2013 's data (DD/MM/YYYY)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" EnableModelValidation="True" GridLines="Horizontal"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:TemplateField HeaderText = "Date">
<ItemTemplate>
<asp:Label ID="Date" Runat="Server"
Text='<%# Eval("DUTY_DATE", "{0:dddd,MMMM dd,yyyy}") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Role">
<ItemTemplate>
<asp:Label ID="Role" Runat="Server"
Text='<%# Eval("DUTY_DESC") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's Name">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("FULLNAME") %>' NavigateUrl='<%# Eval("ROW_PASS", "/sites/HQDO/Pages/OfficerDetails.aspx?_ID={0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("MOBILE_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Officer's HomeNo">
<ItemTemplate>
<asp:Label ID="HomeNo" Runat="Server"
Text='<%# Eval("OFFICE_TEL") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:GridView>
and the CodeBehind for next button is below
protected void Button3_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "SELECT CONTACTS.ROWID as ROW_PASS,DUTY_ROTA.DUTY_DATE AS DUTY_DATE,DUTY_ROTA.DUTY_TYPE AS DUTY_TYPE,DUTY_ROTA.DUTY_OFFICER AS DUTY_OFFICER,DUTY_TYPES.DESCRIPTION AS DUTY_DESC,CONTACTS.SNAME AS FULLNAME,CONTACTS.MOBILE AS MOBILE_NO,CONTACTS.OFFICETEL AS OFFICE_TEL FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE+18 and SYSDATE+36 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
}
I tried to catch the value in below way
LabelDate.Text = GridView1.Rows[0].Cells[0].Text;
And then convert it to Date and use it in my SQL. But the LabelDate.Text is unable to store the data not sure why.
Can you buddies please help How could I Capture GridView First Row First Cells data and Add 18 days to it...also I want to use it in my SQL.
You need to add a handler for GridView.RowDataBound
Here's a quick example:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LabelDate.Text = e.Row.Cells[0].Text;
}
Try :
LabelDate.Text = Convert.ToDateTime(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
LabelDate.Text = DateTime.Parse(GridView1.Rows[0].Cells[0].Text).AddDays(18).ToShortDateString();
Or:
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("fr-FR");
Label1.Text = DateTime.ParseExact(GridView1.Rows[0].Cells[3].Text, "g", provider).AddDays(18).ToShortDateString();

Asp.net GridView RowUpdating returning old values

I am trying to make an editable GridView, and when RowUpdating is called the values I get from the TextBoxes are the old values and not the new ones.
My GridView:
<asp:GridView ID="GVProducts" runat="server" AutoGenerateColumns="False"
CellPadding="4" BackColor="White" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" DataKeyNames="phoneId"
onrowcancelingedit="GVProducts_RowCancelingEdit"
onrowdeleting="GVProducts_RowDeleting"
onrowediting="GVProducts_RowEditing" onrowupdating="GVProducts_RowUpdating"
>
<Columns>
<asp:CommandField ButtonType="Button" EditText="ערוך" HeaderText="עריכה"
InsertText="הוסף" NewText="חדש" SelectText="בחר" ShowEditButton="True"
UpdateText="עדכן" CancelText="בטל" DeleteText="מחק"
InsertVisible="False" CausesValidation="False" />
<asp:CommandField ButtonType="Button" CancelText="בטל" DeleteText="מחק"
EditText="ערוך" InsertText="הוסף" NewText="חדש" SelectText="בחר"
ShowDeleteButton="True" UpdateText="עדכן" HeaderText="מחיקה"
CausesValidation="False" />
<asp:BoundField DataField="phoneId" HeaderText="מספר מכשיר" ReadOnly="True"
SortExpression="phoneId" />
<asp:TemplateField HeaderText="צבע">
<ControlStyle Width="100px" />
<FooterStyle Width="100px" />
<HeaderStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="חברה">
<ItemTemplate>
<asp:Label ID="lblBrand" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="דגם">
<ItemTemplate>
<asp:Label ID="lblModel" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="כמות" SortExpression="amount">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("amount") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("amount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="כמות מינימלית" SortExpression="minAmount">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("minAmount") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("minAmount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="price" HeaderText="מחיר" SortExpression="price" />
<asp:TemplateField HeaderText="תמונה">
<ItemTemplate>
<asp:Image ID="img" runat="server"
ImageUrl='<%# DataBinder.Eval(Container.DataItem,"pic","images/{0}") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
My RowEditing (UpdateGVLabel is not related):
protected void GVProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
GVProducts.EditIndex = e.NewEditIndex;
GVProducts.DataSource = products;
UpdateGVlabel();
//products = connection.GetData("Select * From Products", "Products");
if (products.Rows.Count > 0)
{
((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[6].Controls[1]).Text = products.Rows[e.NewEditIndex][4].ToString();
((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[7].Controls[1]).Text = products.Rows[e.NewEditIndex][5].ToString();
}
}
My RowUpdating (UpdateGVLabel is not related):
protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool abort = false;
int amount = 0, minAmount = 0;
int id = int.Parse(GVProducts.Rows[e.RowIndex].Cells[2].Text);
try
{
amount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[6].Controls[1]).Text);
minAmount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[7].Controls[1]).Text);
if (amount < minAmount)
{
MessageBox.Show("אין אפשרות להגדיר כמות שקטנה מהכמות המינימלית!");
abort = true;
}
if (minAmount <= 0)
{
MessageBox.Show("כמות מינימלית לא יכולה להיות אפס או פחות!\nאם ברצונך לציין שהחנות לא מוכרת את המכשיר הזה, יש ללחוץ על \"מחק\"");
abort = true;
}
if (amount < 0)
{
MessageBox.Show("כמות לא יכולה להיות שלילית");
abort = true;
}
}
catch (FormatException)
{
MessageBox.Show("כמויות חייבות להיות מספרים!");
abort = true;
}
if (!abort)
{
connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
products = connection.GetData("Select * From Products", "Products");
connection.ChangeDatabase(cmd); GVProducts.EditIndex = -1;
GVProducts.DataSource = products;
UpdateGVlabel();
MessageBox.Show("המכשיר נערך בהצלחה!");
}
}
Thanks!
Try this
protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//your code
if (!abort)
{
connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
cmd.ExecuteNonQuery();//OR "connection.ChangeDatabase(cmd);" if it updates your database
products = connection.GetData("Select * From Products", "Products");
GVProducts.EditIndex = -1;
GVProducts.DataSource = products;
GVProducts.DataBind();
UpdateGVlabel();
MessageBox.Show("המכשיר נערך בהצלחה!");
}
}
The problem was you were calling connection.ChangeDatabase(cmd); to update your database after fetching data from table like this products = connection.GetData("Select * From Products", "Products"); hence you always got old values from your db and values in your db also got updated too..
Also add this GVProducts.DataBind(); after providing datasource GVProducts.DataSource = products; to bind the grid.
Write The code in the row updating
int i=convert.toint32(e.NewValues["Standard"])
IsPostBack() is the answer. We have to check if the Page is posted back or not. If not, then we will bind the Grid.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
Reference : https://taditdash.wordpress.com/2014/06/30/why-gridview-rowupdating-event-is-not-giving-the-updated-values/

Categories

Resources