Asp.net GridView RowUpdating returning old values - c#

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/

Related

Column sum of only visible row

I am trying to calculate the sum of the grand total column and showing it to the footer of the gridview, which I am able to achieve it. However I have a condition which makes some rows invisible from the gridview, but it is also summing the value of the rows which are invisible. How to sum the column value only for the rows which are visible?
Below is my gridview:
<asp:GridView ID="GridView9" runat="server" AllowPaging="false" AutoGenerateColumns="False"
ShowFooter="true" BackColor="White" DataKeyNames="ID" BorderColor="#999999" CssClass="tableUserInfo"
GridLines="Vertical" ShowHeaderWhenEmpty="True" PageSize="10" OnRowDataBound="GridView9_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="SessionId" Visible="true">
<ItemTemplate>
<asp:TextBox ID="txt_GSessionId" runat="server" Text='<%# Eval("SessionId") %>' ReadOnly="true"
Visible="false"></asp:TextBox>
</ItemTemplate>
<HeaderStyle Width="10%" />
<ItemStyle Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer" Visible="true">
<ItemTemplate>
<asp:Label ID="lblCustomerName" Font-Size="11px" runat="server" Text='<%# Eval("CustomerName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="G_Total" Visible="true">
<ItemTemplate>
<asp:Label ID="lblGTotal" Font-Size="11px" runat="server" Text='<%# Eval("GTotal","{0:n}") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<FooterStyle Width="30%" />
<HeaderStyle Width="8%" />
<ItemStyle Width="8%" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="Black" ForeColor="Red" Width="100%" Wrap="false" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Here is my code behind:
decimal grdTotal;
protected void GridView9_RowDataBound(object sender, GridViewRowEventArgs e)
{
txt_SessionId.Text = ddlSession.SelectedValue;
foreach (GridViewRow row2 in GridView9.Rows)
{
TextBox sid = row2.FindControl("txt_GSessionId") as TextBox;
int a, b;
a = int.Parse(sid.Text);
b = int.Parse(txt_SessionId.Text);
if (a == b)
{
row2.Visible = true;
}
else
{
row2.Visible = false;
}
}
if (e.Row.Visible && e.Row.RowType == DataControlRowType.DataRow)
{
decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "GTotal"));
grdTotal = grdTotal + rowTotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
Label lbl1 = (Label)e.Row.FindControl("lblLabourTotal");
lbl.Font.Size = 12;
lbl.Text = "Rs. " + grdTotal.ToString("0");
lbl.ForeColor = System.Drawing.Color.White;
}
}

How to make grid view footer controls visible if grid view is empty

I have a grid view control in my page that indexes all the Lecture Contents. I have added a Text Box control and a Link Button. But for the Lectures that have no Content yet, the Grid View does not appear.
Have tried many references, as a result the footer has appeared but I am not able to insert data using the Controls in the footer.
My main objective is to make the Controls behave same in both scenarios.
Here is the Grid View Code.
`<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="No Contents found for this lecture." ShowFooter="true" HeaderStyle-Wrap="false" Width="70%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText=" LectureID " SortExpression="lecc_id">
<ItemTemplate>
<asp:Label ID="lbllecc_id" runat="server" Text='<%# Bind("lecc_id") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbllecc_id" runat="server" T`enter code here`ext="Create New">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Content " SortExpression="lecc_contents">
<EditItemTemplate>
<asp:TextBox ID="tblecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbllecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtcontent" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfcontent" runat="server" ErrorMessage="Content field cannot be blank." ControlToValidate="txtcontent" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:LinkButton ID="createcontent" runat="server" OnClick="createcontent" CssClass="btn-sm btn-default">Insert Content</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</EmptyDataTemplate>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Font-Size="17px" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" Font-Bold="False" Font-Size="14px" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>`
and the code behind functions for grid view.
`protected void Page_Load(object sender, EventArgs e){
if (Session["fac_username"] != null)
{
String username = Convert.ToString(Session["fac_username"]);
if (!IsPostBack)
{
BindGridViewData();
}
}
else
{
Response.Redirect("~/Account/Login.aspx");
}
}protected void BindGridViewData(){
int lecID = Convert.ToInt32(Session["lecID"]);
GridView1.DataSource = DataAccessLayer.getAllContents(lecID);
GridView1.DataBind();} protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){
}
protected void createcontent(object sender, EventArgs e){
int lecID = Convert.ToInt32(Session["lecID"]);
con.Open();
SqlCommand command = new SqlCommand("insert into uni_lect_content(lecc_id, lecc_contents) values(#lecc_id, #lecc_contents)", con);
command.Parameters.AddWithValue("#lecc_id", lecID);
command.Parameters.AddWithValue("#lecc_contents", ((TextBox)GridView1.FooterRow.FindControl("txtcontent")).Text);
command.ExecuteNonQuery();
con.Close();
lblmsg.Text = "New Course Successfully Created..!";}`
DataAccessLayer class's getAllConents() method is here.
`public class AllContents
{
public long lecc_id { get; set; }
public string lecc_contents { get; set; }
}
public class DataAccessLayer
{
public static List<AllContents> getAllContents( int lecID){
List<AllContents> listAll = new List<AllContents>();
string cs = ConfigurationManager.ConnectionStrings["ILMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand com = new SqlCommand("select lecc_id, lecc_contents from uni_lect_content, uni_lectures, uni_offered_courses where uni_lect_content.lecc_id = uni_lectures.lec_id and uni_lectures.cours_offer_id = uni_offered_courses.cours_offer_id and lecc_id = '"+lecID+"'", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
while (rdr.Read())
{
AllContents obj = new AllContents();
obj.lecc_id = Convert.ToInt32(rdr["lecc_id"]);
obj.lecc_contents = rdr["lecc_contents"].ToString();
listAll.Add(obj);
}
}
return listAll;
}`
Help me out of this situation.
Thanks in advance.
FRONT END GRDIVIEW
<asp:GridView ID="grdview" ShowFooter="true" OnRowEditing="grdview_RowEditing" OnRowCancelingEdit="grdview_RowCancelingEdit" OnRowCommand="grdview_RowCommand" OnRowUpdating="grdview_RowUpdating" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="SR No.">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
<asp:Label ID="lblid" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp Name">
<ItemTemplate>
<asp:Label ID="elblempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempname" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp No">
<ItemTemplate>
<asp:Label ID="elblempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempno" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Email">
<ItemTemplate>
<asp:Label ID="elblempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempemail" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Age">
<ItemTemplate>
<asp:Label ID="elblempage" runat="server" Text='<%#Eval("Age") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempage" runat="server" Text='<%#Eval("Age") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempage" runat="server" ></asp:TextBox>
<asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
BACKEND CODE
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grdview.DataSource = ds;
grdview.DataBind();
int columncount = grdview.Rows[0].Cells.Count;
grdview.Rows[0].Cells.Clear();
grdview.Rows[0].Cells.Add(new TableCell());
grdview.Rows[0].Cells[0].ColumnSpan = columncount;
grdview.Rows[0].Cells[0].Text = "No Records Found";
if (e.CommandName == "AddNew")
{
TextBox ftxtempname = (TextBox)grdview.FooterRow.FindControl("ftxtempname");
TextBox ftxtempno = (TextBox)grdview.FooterRow.FindControl("ftxtempno");
TextBox ftxtempemail = (TextBox)grdview.FooterRow.FindControl("ftxtempemail");
TextBox ftxtempage = (TextBox)grdview.FooterRow.FindControl("ftxtempage");
using (con)
{
SqlCommand cmd = new SqlCommand("usp_add_upd_emptb", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpName", ftxtempname.Text);
cmd.Parameters.AddWithValue("#EmpNo", ftxtempno.Text);
cmd.Parameters.AddWithValue("#Desig", ftxtempage.Text);
cmd.Parameters.AddWithValue("#Email", ftxtempemail.Text);
con.Open();
cmd.ExecuteNonQuery();
}
This is a working complete code.

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

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.

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

Categories

Resources