asp.net gridview sum and quantity of the columns - c#

i have a small problem with summarizing of the total value of the columns. I have a shopping cart where i want to summarize quantity and price of the item. I've done summarize of prices but when i was trying to multiply it to quantity it didn't work.
.
Could you please give me an advice.
Here is a gridview:
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="id" ShowFooter="true" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="item" HeaderText="Item" SortExpression="item"></asp:BoundField>
<asp:BoundField DataField="BEE" HeaderText="Description" SortExpression="BEE"></asp:BoundField>
<asp:BoundField DataField="count" HeaderText="Quantity" SortExpression="count"></asp:BoundField>
<asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price"></asp:BoundField>
<asp:TemplateField>
<FooterTemplate>
<asp:Label ID="lbltxtTotal" runat="server" Text="Total Price" />
</FooterTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"></asp:BoundField>
<asp:ButtonField CommandName="Delete" Text="Delete" ButtonType="Button" ShowHeader="True" HeaderText="Delete"></asp:ButtonField>
</Columns>
<EmptyDataTemplate>No Record Available</EmptyDataTemplate>
<FooterStyle BackColor="White" Font-Bold="True"></FooterStyle>
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Right" BackColor="White" ForeColor="Black"></PagerStyle>
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#F7F7F7"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#4B4B4B"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#E5E5E5"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#242121"></SortedDescendingHeaderStyle>
</asp:GridView>
and here is a backend:
protected void Timer1_Tick(object sender, EventArgs e)
{
string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
string Username_new = Username.Replace("APAC\\", "");
GridView1.DataBind();
//live data
String myquery = "Select * from Basket where Username='" + Username_new + "'";
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.FooterRow.Cells[1].Text = "Total Amount";
GridView1.FooterRow.Cells[2].Text = dt.Compute("Sum(price)", "").ToString();
}

This is easy.
Add method to your code:
protected void getSUM()
{
// SQL query that gets total of product sales where category id = 1
string SqlQuery = #"SELECT SUM(ProductSales) AS TotalSales
FROM [NORTHWIND].[dbo].[Sales by Category]
WHERE CategoryID = 1";
// Declare and open a connection to database
SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString);
conn.Open();
// Creates SqlCommand object
SqlCommand comm = new SqlCommand(SqlQuery, conn);
// Gets total sales
decimal TotalSales = Convert.ToDecimal(comm.ExecuteScalar());
// Close connection
conn.Close();
conn.Dispose();
comm.Dispose();
// Adds formatted output to GridView footer
GridView1.Columns[1].FooterText = String.Format("{0:c}", TotalSales);
}
In markup code, we'll define footer template and call getSUM method:
<FooterTemplate>
Total sales: <%# getSUM(); %>
</FooterTemplate>

Related

Checkbox select row(s) from one GridView (Table) to another back and forth

I have two gridviews each with their own table.
I'm trying to make it so I can select a row(s) from GridViewA and move it to GridViewB (not copy). Then be able to move the selected row(s) from GridViewB back to GridViewA.
GridViewA (populated with SqlDataSource1)
<asp:GridView ID="grdA" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="white" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
GridViewB (populated with SqlDataSource2)
<asp:GridView ID="grdB" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox2" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
Button to move row(s) from GridViewA to GridViewB. It works but I'm not sure how to delete the row from GridViewA after moving to GridViewB
protected void btnSubmit_Click(object sender, EventArgs e)
{
string DataA, DataB, DataC;
var connectionString = ConfigurationManager.ConnectionStrings["Database1"].ConnectionString;
var insertStatement = "INSERT INTO SqlTableB (Data1, Data2, Data3) VALUES (#Data1, Data2, Data3)";
using (var sqlConnection = new SqlConnection(connectionString))
foreach (GridViewRow gRow in grdA.Rows)
{
CheckBox cb = (gRow.FindControl("chkBox") as CheckBox);
if (cb.Checked)
{
DataA = Convert.ToString(gRow.Cells[1].Text);
DataB = Convert.ToString(gRow.Cells[2].Text);
DataC = Convert.ToString(gRow.Cells[3].Text);
using (var sqlCommand = new SqlCommand(insertStatement, sqlConnection))
{
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Data1", DataA);
sqlCommand.Parameters.AddWithValue("#Data2", DataB);
sqlCommand.Parameters.AddWithValue("#Data3", DataC);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
}
}
}
Please let me know if I can make the issue more clear, thank you
I would approach the problem this way:
First, make sure you set the PK row id for the Grid (that way you dont have to include in the display, or markup).
So USE "datakeys" setting of the grid - this will help a lot.
So, say two grids, like this:
<div style="float:left;width: 40%">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveRight" runat="server" Text="Move->" style="float:right" CssClass="btn" OnClick="cmdMoveRight_Click" />
</div>
<div style="float:left;width: 40%;margin-left:10px">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveMoveLeft" runat="server" Text="<-Move" CssClass="btn" OnClick="cmdMoveMoveLeft_Click" />
</div>
Code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrids();
}
}
void LoadGrids()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotelsA");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
cmdSQL.CommandText = "SELECT * from tblHotelsB";
GridView2.DataSource = MyRstP(cmdSQL);
GridView2.DataBind();
}
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
Ok, so now we have this:
Ok, now a button to move right, and one to move left. Code is:
protected void cmdMoveRight_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsB (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsA " +
"WHERE tblHotelsA.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsA WHERE ID = #ID";
MoveRows(GridView1,strSQL,strSQLDel);
}
protected void cmdMoveMoveLeft_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsA (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsB " +
"WHERE tblHotelsB.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsB WHERE ID = #ID";
MoveRows(GridView2, strSQL,strSQLDel);
}
void MoveRows(GridView gv,string strSQL, string strSQLDel)
{
foreach (GridViewRow OneRow in gv.Rows)
{
CheckBox ckBox = OneRow.FindControl("cHkSel") as CheckBox;
if (ckBox.Checked)
{
int PKID = (int)gv.DataKeys[OneRow.RowIndex]["ID"];
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
SqlRun(cmdSQL);
// delte the row
cmdSQL.CommandText = strSQLDel;
SqlRun(cmdSQL);
}
}
// now re-load both grids to reflect changes
LoadGrids();
}
public void SqlRun(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}

Still have problems with gridview and update for my database project

I want to Update An Number of goals That a Player Scored so if he socred a goal I want to do an update for his number of goals...
I got an Error in my Code And I don't know how to fix it. Can anyone help me to fix it, please ?
My Code:
string connectionStr = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|\SoccerDataBase.mdb";
using (OleDbConnection sqlCon = new OleDbConnection(connectionStr))
{
sqlCon.Open();
string queryStr = "SELECT Achievement FROM SoccerAchievements WHERE UserID=#AchNums";
OleDbCommand sqlCmd = new OleDbCommand(queryStr, sqlCon);
sqlCmd.Parameters.AddWithValue("#AchNums", (SoccerTable.FooterRow.FindControl("AchNums") as TextBox).Text.Trim());
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(queryStr, sqlCon);
DataSet ds = new DataSet();
dataAdapt.Fill(ds, "SoccerAchievement");
DataRow row = ds.Tables["SoccerAchievement"].Rows[0];
int a = int.Parse(row[3].ToString());
a = a + int.Parse("#AchNums");
string query = "UPDATE SoccerAchievements SET Achievement= '" + a + "' WHERE UserID= #AchNums";
sqlCmd.ExecuteNonQuery();
}
My GridView HTML CODE:
<asp:GridView ID="SoccerTable" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataSourceID="AccessDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="קוד שחקן" InsertVisible="False"
SortExpression="ID" />
<asp:BoundField DataField="Team" HeaderText="קבוצות" SortExpression="Team" />
<asp:BoundField DataField="Players" HeaderText="שחקנים"
SortExpression="Players" />
<asp:TemplateField HeaderText="הישגים">
<FooterTemplate>
<asp:TextBox ID="AchNums" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button class = "AddButton" ID="AddButton" runat="server" onclick="AddButton_Click" Text="עדכן" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
My Error: There is no row at position 0.
Image:
My Data SoccerAchievements
Image:
Please help me guys :)
Replace this
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(queryStr, sqlCon);
With
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(sqlCmd);
However you may again face error at your int.parse code.please correct that as well.

Display Multiple Images in a gridview

I want to display multiple images in a gridview within a single row at a time.
Also I want to make sure that for multiple images uploaded at a time there should be only one row gets inserted into the table.
See my BindGrid() code;-
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
SqlCommand cmd = new SqlCommand("Select Id, gallery_id, image_title, image_description, image_path from tbl_gallery_stack order by Id desc");
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
grdGalleryData.DataSource = dt;
grdGalleryData.DataBind();
}
}
}
}
Also see the HTML for gridview:-
<asp:GridView ID="grdGalleryData"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="10"
OnPageIndexChanging="grdGalleryData_PageIndexChanging"
CssClass="hoverTable"
DataKeyNames="Id">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="gallery_id" HeaderText="Id" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_title" HeaderText="Gallery title" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_description" HeaderText="Gallery Description" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Images" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:Image ID="imgDisplay" runat="server" ImageUrl='<%#Getimage(Eval("image_path").ToString()) %>' Width="100px" Height="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I propose to you visit web site : https://social.msdn.microsoft.com/Forums/windowsapps/en-US/0565b55e-3daf-4eef-85ac-a8ab72af4e68/displaying-the-images-into-the-gridview / regularly !
It seems you are querying the data as row-per-image instead of row-with -related-images. So you need to change the database query pattern to something like below (Its just for demonstration purpose to hold nested dataset):
void BindGrid()
{
using (SqlConnection con = new SqlConnection("YOUR CONNECTION STRING"))
{
using (SqlDataAdapter personAdapter = new SqlDataAdapter("SELECT * FROM PersonTable", con))
using (SqlDataAdapter personImagesAdapter = new SqlDataAdapter("SELECT * FROM PersonImages", con))
{
DataSet dataSet = new DataSet("PersonAndImagesDataSet");
personAdapter.Fill(dataSet, "PersonTable");
personImagesAdapter.Fill(dataSet, "PersonImages");
DataRelation personWithImages = dataSet.Relations.Add("PersonAndImages", dataSet.Tables["PersonTable"].Columns["Id"],
dataSet.Tables["PersonImages"].Columns["Person_Id"]);
if (grdGalleryData.DataSource == null)
{
grdGalleryData.DataSource = dataSet.Tables["PersonTable"];
grdGalleryData.DataBind();
}
}
}
}
In the HTML you can include a ListView (or a control of your choice to hold list items) and on GridView's databind event do something like this:
ASPX View
<asp:GridView ID="grdGalleryData"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="3"
CssClass="hoverTable"
DataKeyNames="Id" OnRowDataBound="grdGalleryData_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="Name" HeaderText="Gallery title" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Images" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ListView runat="server" ID="lvImages" OnDataBinding="lvImages_DataBinding" >
<ItemTemplate>
<asp:Image ID="imgDisplay" runat="server" ImageUrl='<%#Eval("ImagePath")%>' Width="50px" Height="50px" />
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Databinding to ListView (C#)
protected void grdGalleryData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var personId = Convert.ToInt32((e.Row.DataItem as DataRowView)["Id"]);
var imageListView = e.Row.FindControl("lvImages") as ListView;
//Just for demo purpose. Get only required image data based on the parent table id in actual code.
if (data == null)
{
data = GetData();
}
//In below line, based on the parent table id , get the image data from data store. Just for brevity I am querying a complete dataset on every row data bind.
//E.g: var resultRows = DataStore.GetImage(int personId); and bind this to ListView directly.
var resultRows = data.Tables["PersonImages"].AsEnumerable().Where(img => img.Field<int>("Person_Id") == personId);
DataTable dtImages = new DataTable();
if (resultRows != null && resultRows.Count()>0)
dtImages = resultRows.CopyToDataTable();
imageListView.DataSource = dtImages; //Here you should be assigning result table/collection that you get from data store.
imageListView.DataBind();
}
}
Hope this help you.

Grid view index changing with filters

I got this simple gridview
<asp:GridView ID="GridViewFoundations" runat="server" AutoGenerateColumns="False"
Width="100%" AllowPaging="True" AllowSorting="True" PageSize="15"
CellPadding="4" ForeColor="#333333" GridLines="None"
onpageindexchanging="GridViewFoundations_PageIndexChanging">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate><asp:Label ID="lb_id" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "nodeId") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Foundation Name">
<ItemTemplate><asp:Label ID="lb_foundationName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "text") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastUpdate">
<ItemTemplate><asp:Label ID="lb_lastUpdate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "updateDate") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expire Date">
<ItemTemplate><asp:Label ID="lb_expireDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "expireDate") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
Then I bind if on the page load event , like this
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void BindData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And i have the following filter (for example by text)
protected void btn_filtro_Click(object sender, EventArgs e)
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
My problem is I can't change the index of the page and keep my filters on..
I have already tried
GridViewFoundations.PageIndex = e.NewPageIndex
followed by
gridviewFoundations.Databind() or BindData()
but in the 1st case the gridview desapears and in the second it clears all the filters (obviously) .
So Can anyone help me changing the page of the grid with filters?
In first case(GridViewFoundations.PageIndex = e.NewPageIndex followed by gridviewFoundations.Databind() ) data disappears as you are not providing any datasource to rebing your grid after postback.
In second case(BindData()) you are binding grid without any filters, hence your filter is lost.
what you can do is create a new function
protected void BindFilteredData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
else
BindFilteredData();
}
This will call BindData when your page loads first time and rest of the times it will call filtered data function.

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

Categories

Resources