Gridview fields values does not change on update - asp.net

I have a gridview and i want to modify some fields on gridview.This fields value not change when i click on Update button.I tried use Postback control but this problem keep going.How can i solve this problem?
ASPX code
<asp:GridView ID="gview" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" GridLines="Horizontal" OnRowDataBound="gview_RowDataBound" OnRowEditing="gview_RowEditing" OnRowUpdating="gview_RowUpdating" OnRowCancelingEdit="gview_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="SubCategoryId" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="SubCategoryId" />
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCategory" DataValueField="CategoryId" DataTextField="CategoryName" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:CommandField ButtonType="Link" EditText="Edit" HeaderText="Edit"
ShowEditButton="True" ShowHeader="False" CancelText="Cancel" UpdateText="Update" />
</Columns>
</asp:GridView>
C# code
protected void gview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = e.Row.FindControl("lblCategory") as Label;
DropDownList ddl = e.Row.FindControl("ddlCategory") as DropDownList;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddl.DataSource = LoadCategories();
ddl.DataBind();
}
if (lbl != null)
{
lbl.Text = GetCategoryName(Convert.ToInt32(gview.DataKeys[e.Row.RowIndex][0]));
}
}
}
protected void gview_RowEditing(object sender, GridViewEditEventArgs e)
{
gview.EditIndex = e.NewEditIndex;
SubCategoryLoad();
}
protected void gview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int categoryId, subCategoryId;
string categoryName;
DropDownList ddl = (DropDownList)gview.Rows[e.RowIndex].FindControl("ddlCategory");
subCategoryId = int.Parse(gview.Rows[e.RowIndex].Cells[0].Text);
categoryId = int.Parse(ddl.SelectedValue);
categoryName = gview.Rows[e.RowIndex].Cells[2].Text;
gview.EditIndex = -1;
UpdateSubCategory(subCategoryId,categoryName,categoryId);
SubCategoryLoad();
}
public void SubCategoryLoad()
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "SELECT * FROM dbo.SubCategories";
using (SqlDataAdapter da = new SqlDataAdapter(query, conn))
{
DataTable dt = new DataTable();
da.Fill(dt);
gview.DataSource = dt;
gview.DataBind();
}
}
}
public int UpdateSubCategory(int subCategoryId, string categoryName, int categoryId)
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "UPDATE dbo.SubCategories SET CategoryId = #categoryId, CategoryName = #categoryName WHERE SubCategoryId = #id";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#id", subCategoryId);
cmd.Parameters.AddWithValue("#categoryName", categoryName);
cmd.Parameters.AddWithValue("#categoryId", categoryId);
return (int)cmd.ExecuteNonQuery();
}
}
}

Please check have you bind gridview inside
if(!page.ispostback)
{
}

You must update the data to the actual datasource and rebind it.
If you have updated the values then you shall rebind the GridView again with updated values
mGridView.DataSource = {YOUR DATA SOURCE};
mGridView.DataBind();
EDIT 1:
Does this method being called break there check that
have you set update as
commandText ="Update"

Related

I can't paint the rows of another page in the gridview, asp.net

I can't solve one thing, I want to paint some rows of the GridView depending on a column. I have no problems with this, but when I change the page, I can't get it to paint.
This is how I do the pagination
GridView2.PageIndex = e.NewPageIndex;
loadgrid();
paintpagin(e.NewPageIndex);
So I try to paint it
GridView2.PageIndex = newPageIndex;
foreach (GridViewRow Rowe in GridView2.Rows)
{
CheckBox Rc = (CheckBox)Rowe.FindControl("rdaprobar");
RadioButton Ri = (RadioButton)Rowe.FindControl("rdpendiente");
RadioButton Rd = (RadioButton)Rowe.FindControl("rdCandelar");
if (Rc.Checked == true)
{
GridView2.Rows[Rowe.DataItemIndex].BackColor = ColorTranslator.FromHtml("#bcf5be");
}
}
The even to use for highlights, formatting, etc.?
use the Grid row data bound event.
So, first up, our markup:
<asp:GridView ID="GHotels" runat="server" CssClass="table" AutoGenerateColumns="false"
width="45%" DataKeyNames="ID" OnRowDataBound="GHotels_RowDataBound" AllowPaging="True"
OnPageIndexChanging="GHotels_PageIndexChanging" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:TemplateField HeaderText="HotelName">
<ItemTemplate>
<asp:Label ID="txtHotel" runat="server" Text='<%# Eval("HotelName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />
</Columns>
<PagerStyle CssClass="GridPager" />
</asp:GridView>
Code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT * FROM tblHotels WHERE Description is not null ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
DataTable rstData = new DataTable();
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
GHotels.DataSource = rstData;
GHotels.DataBind();
}
}
}
Our pager code (and NOTE YOU HAVE the load of the grid before the pager - chec your code!!!).
protected void GHotels_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GHotels.PageIndex = e.NewPageIndex;
LoadData();
}
Ok, we now have this:
Now, I highlight each hotel if it is active. NOTE very careful, I don't have that column "active" in the GV, but it was/is part of the data source. So, for bonus points, I demonstrate how to get/grab/use columns that you don't render or have in the GV, but in fact is part of the data source.
So, our code to highlight, we have this:
protected void GHotels_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get binding data source
DataRowView gData = e.Row.DataItem as DataRowView;
if ((bool)gData["Active"]) {
// Label tHotel = e.Row.FindControl("txtHotel") as Label;
// tHotel.BackColor = System.Drawing.Color.LightSteelBlue;
e.Row.Cells[2].BackColor = System.Drawing.Color.LightSteelBlue;
}
}
}
So, we now have this:
So do NOT try and loop each row of the GV - use the row data bound to highlight and format as per above.

SelectCommand.Connection property has not been initialized when excute comand with ID from gridview

Please advice me to correct my code, i want to retrieve data to a textbox from grid-view, passing "ID" as parameter on link clicked event in grid view ,but it does not work as expected,
My ASPX code :
<asp:GridView ID="gvcat" CssClass="table table-bordered font-13" Width="500px" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" CommandArgument='<%# Eval("ID") %>' OnClick="lnkView_Click">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And behide code:
protected void lnkView_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
int ID = Convert.ToInt32((sender as LinkButton).CommandArgument);
using (SqlCommand cmd = new SqlCommand("SELECT * from tblCategory WHERE ID = #ID , con"))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dtcategory = new DataTable();
sda.Fill(dtcategory);
con.Close();
hfID.Value = ID.ToString();
txtName.Text = dtcategory.Rows[0]["Name"].ToString();
txtDescription.Text = dtcategory.Rows[0]["Description"].ToString();
}
}
}
}
protected void lnkView_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
int ID = Convert.ToInt32((sender as LinkButton).CommandArgument);
using (SqlCommand cmd = new SqlCommand("SELECT * from tblCategory WHERE ID = #ID",con))
{
cmd.Parameters.AddWithValue("#ID",ID); // this line was mising in your code
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dtcategory = new DataTable();
sda.Fill(dtcategory);
con.Close();
hfID.Value = ID.ToString();
txtName.Text = dtcategory.Rows[0]["Name"].ToString();
txtDescription.Text = dtcategory.Rows[0]["Description"].ToString();
}
}
}
}
I try to correct as you guide and i got a new error message when i click on linkview,
{"Must declare the scalar variable \"#ID\"."}
although a already define #ID in my code,

how to calculate total price in gridview in ASP.NET

I have a gridview in ASP.NET,In that gridview there is one column of total price.I want to show to total price of all rows below the gridview and also if i will update or delete any row then it should update that total computed price.
Can anyone please help in this.
Thanks in advance.
The HTML Markup consists of an ASP.Net GridView. The ShowFooter property is set to true so that the GridView’s Footer Row is displayed.
Paging has been enabled for the GridView and OnPageIndexChanging event handler has been assigned.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" ShowFooter="true">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="Order ID" ItemStyle-Width="60" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" ItemStyle-Width="210" />
<asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-Width="60" DataFormatString="{0:N2}"
ItemStyle-HorizontalAlign="Right" />
</Columns>
</asp:GridView>
code behind.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string query = "SELECT TOP 30 OrderID,";
query += "(SELECT ProductName FROM Products WHERE ProductID = details.ProductId) ProductName,";
query += "(Quantity * UnitPrice) Price";
query += " FROM [Order Details] details";
query += " ORDER BY OrderID";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
//Calculate Sum and display in Footer Row
decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>("Price"));
GridView1.FooterRow.Cells[1].Text = "Total";
GridView1.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
GridView1.FooterRow.Cells[2].Text = total.ToString("N2");
}
}
}
}
}

method of populate dropdownlist inside gridview

If i want to populate a DropdownList in a GridView what will be the best way? use GridView 'OnRowDataBound' event and fetch query everytime to db or get all data first and put it on datatable and do further work from this datatable ?
As your question is unclear about your requirement, I assume that you want to bind dropdownlist inside the Gridview using OnRowDataBound event of gridview.
So here are the steps:-
Add a Gridview HTML in your aspx page with DropDownList in ItemTemplate of TemplateField.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField HeaderText="Name" DataField="ContactName" />
<asp:TemplateField HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' Visible = "false" />
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you need to bind the gridview with records which will come from the database.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT ContactName, Country FROM Customers");
GridView1.DataBind();
}
}
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
Then the code for OnRowDataBound will follow like below :-
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}
See the Reference link for your reference
Also see the Working demo for your reference
Hope that helps.

How to add new row in a gridview on button click

I am new to asp.net and i want to add new row in a gridview on button click... see my code kindly help me..its been 2 days i am working on it but didn't find the solution....
HTML CODE
<div>
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
DataKeyNames="PRODUCTID" CellPadding="3" GridLines="Both" OnRowEditing="gridOnRowEditing"
OnRowCancelingEdit="gridOnRowCancelingEdit" OnRowUpdating="gridOnRowUpdating">
<HeaderStyle BackColor="Cyan" ForeColor="White" BorderColor="Red" />
<Columns>
<asp:CommandField ButtonType="Button" ShowCancelButton="true" ShowEditButton="true"
HeaderText="Edit & Update" />
<asp:BoundField DataField="PRODUCTID" HeaderText="PRODUCT ID" ReadOnly="true" />
<asp:TemplateField HeaderText="PRODUCT NAME">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtProduct1" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtProduct" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIT PRICE">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtPrice1" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPrice" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" OnClick="button1_click" ID="button1" Text="Add New Row" />
<%-- <input type="button" id="btnNew" value="Add New" onclick="addNew()" />--%>
</div>
C SHARP CODE
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=practice;Integrated Security=true;");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From PRODUCTDETAILS order by PRODUCTID asc", con);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["CurrentTable"] = dt;
}
protected void gridOnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridOnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void gridOnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox txtProductName = (TextBox)row.FindControl("txtProduct");
TextBox UNITPRICE = (TextBox)row.FindControl("txtPrice");
string ProductName = txtProductName.Text;
string txtUnitPrice = UNITPRICE.Text;
int ProductID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
UpdateRecord(ProductID, ProductName, txtUnitPrice);
}
protected void UpdateRecord(int ProductID, string ProductName, string UnitPrice)
{
try
{
SqlCommand cmd = new SqlCommand("Update PRODUCTDETAILS set ProductName=#ProductName,UnitPrice=#UnitPrice WHERE ProductID=#ProductID", con);
cmd.Parameters.Add(new SqlParameter("#ProductID", ProductID));
cmd.Parameters.Add(new SqlParameter("#ProductName", ProductName));
cmd.Parameters.Add(new SqlParameter("#UnitPrice", UnitPrice));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
catch (Exception ex)
{
throw ex;
}
}
protected void AddNewRow()
{
//dt = new DataTable();
//DataRow dr = null;
//dt.Columns.Add(new DataColumn("PRODUCTID", typeof(string)));
//dt.Columns.Add(new DataColumn("PRODUCTNAME", typeof(string)));
//dt.Columns.Add(new DataColumn("UNITPRICE", typeof(string)));
//dr = dt.NewRow();
//dr["PRODUCTID"] = 14;
//dr["PRODUCTNAME"] = string.Empty;
//dr["UNITPRICE"] = string.Empty;
//dt.Rows.Add(dr);
//ViewState["CurrentTable"] = dt;
//GridView1.DataSource = dt;
//GridView1.DataBind();
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
int ProductID = Convert.ToInt32(GridView1.DataKeys[rowIndex].Value);
TextBox TextBoxName = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtProduct1");
TextBox TextBoxPrice = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtPrice1");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["PRODUCTID"] = ProductID + 1;
drCurrentRow["PRODUCTNAME"] = TextBoxName.Text;
drCurrentRow["UNITPRICE"] = TextBoxPrice.Text;
//dtCurrentTable.Rows[13 - 1]["PRODUCTID"] = ProductID + 1;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
protected void button1_click(object sender, EventArgs e)
{
AddNewRow();
}
}
}

Resources