(Gridview)1st record is being deleted from database c# - 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;
}
}
}

Related

No Overload for method which takes 4 arguments

I am trying to update gridview. Here, I have used 3 tier architecture method.
Here is my GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ResllerID"
ForeColor="#333333" GridLines="None" OnRowDeleting="DeleteRecord" EmptyDataText="There are no data records to display."
AllowPaging="True" AllowSorting="True" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Reseller Name" SortExpression="ResellerName">
<EditItemTemplate>
<asp:TextBox ID="ResellerTextBox" runat="server" Text='<%# Bind("ResellerName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ResellerName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile Number" SortExpression="MobileNumber">
<EditItemTemplate>
<asp:TextBox ID="MobileTextBox" runat="server" Text='<%# Bind("MobileNumber") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("MobileNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reference Number" SortExpression="ReferenceNumber">
<EditItemTemplate>
<asp:TextBox ID="ReferenceTextBox" runat="server" Text='<%# Bind("ReferenceNumber") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ReferenceNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
Here is my code: I am getting error ResellerBL.UpdateReseller(resellerId, name.Text, mobileNumber.Text, referenceNumber.Text); It says No Overload for method which takes 4 arguments
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ResellerBL.GetResellers();
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int resellerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
TextBox mobileNumber = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
TextBox referenceNumber = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];
ResellerBL.UpdateReseller(resellerId, name.Text, mobileNumber.Text, referenceNumber.Text);
GridView1.EditIndex = -1;
GridView1.DataSource = ResellerBL.GetResellers();
GridView1.DataBind();
}
ResellerBL code:
public static void UpdateReseller(Reseller reseller)
{
string query = "UPDATE [Resellers] SET [ResellerName] = #ResellerName, [ReferenceNumber] = #ReferenceNumber WHERE [ResellerID] = #ResellerID";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#ResellerName", SqlDbType.Text).Value = reseller.ResellerName;
cmd.Parameters.AddWithValue("#MobileNumber", SqlDbType.Text).Value = reseller.MobileNumber;
cmd.Parameters.AddWithValue("#ReferenceNumber", SqlDbType.Text).Value = reseller.ReferenceNumber;
cmd.Parameters.AddWithValue("#ResllerID", SqlDbType.Text).Value = reseller.ResllerID;
DbUtility.UpdateDb(cmd);
}
You are calling it with four arguments:
ResellerBL.UpdateReseller(resellerId, name.Text, mobileNumber.Text, referenceNumber.Text);
But it only accepts one:
public static void UpdateReseller(Reseller reseller)
Two options are
Create a new reseller object and pass that:
.
var myreseller = New Reseller();
myresller.Id = resellerId;
//etc
ResellerBL.UpdateReseller(myreseller);
OR
Modify the (or add an overloaded) method to take the four arguments:
.
public static void UpdateReseller(int resellerId, string resellerName, string resellerMobile, string resellerRefNum)
Your UpdateReseller method takes a single parameter: A reseller.
If you want to be able to pass individual parts to the method, you need to modify the signature or create an overload with the appropriate parameters.

Unable to get data from TextBox/DDL in Gridview

I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;

Issue with updating rows in a gridview

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`;
}
}

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