Table Rows Disappear on Dropdown ItemSelected - asp.net

Every time I change a dropdown on a webpage, the page "resets". A row I've inserted programmatically disappears and a new one is written. I want to let the user add multiple rows.
I'm attempting to
Use a dropdown to fill mulitple GridViews displaying product infromation
User will add a quantity in a text box
Click 'Add to cart', which will...
Create a new row on an existing Table on that page with the selected product details
This works fine for the first row only, however, if I change the dropdown or click the 'Add to cart' button, the newly inserted row will be overwritten by the row from subsequent updates.
This is my table...
<asp:Table ID="tblOrderPreview" runat="server" BorderStyle="Solid" Width="800px" >
<asp:TableHeaderRow BorderStyle= "Solid"><asp:TableHeaderCell>Product</asp:TableHeaderCell><asp:TableHeaderCell>Qty</asp:TableHeaderCell><asp:TableHeaderCell>Price</asp:TableHeaderCell><asp:TableHeaderCell>Total</asp:TableHeaderCell><asp:TableCell><b>Remove Item</b></asp:TableCell></asp:TableHeaderRow>
<asp:TableRow BorderStyle= "Solid"><asp:TableCell></asp:TableCell><asp:TableCell></asp:TableCell><asp:TableCell></asp:TableCell><asp:TableCell></asp:TableCell><asp:TableCell></asp:TableCell></asp:TableRow>
</asp:Table>
And this is the code the button calls:
Protected Sub btnAddToCart_Click(sender As Object, e As System.EventArgs) Handles btnAddToCart.Click
lblValidator.Visible = False
If txtQuantity.Text <> "" Then
lblValidator.Visible = False
Dim name As String
name = GridView3.Rows(0).Cells(0).Text.ToString
Dim qantity As Integer
qantity = Convert.ToDouble(txtQuantity.Text)
Dim price As String
price = Convert.ToDouble(GridView5.Rows(0).Cells(0).Text.ToString)
Dim total As String
total = "$" + (price * qantity).ToString
'insert new row to tblOrderPreview (count rows, then insert another row named COUNT+1
Dim tRow As New TableRow()
tblOrderPreview.Rows.Add(tRow)
Dim tCellProduct As New TableCell()
tCellProduct.Text = name
tRow.Cells.Add(tCellProduct)
Dim tCellQty As New TableCell()
tCellQty.Text = qantity.ToString
tRow.Cells.Add(tCellQty)
Dim tCellPrice As New TableCell()
tCellPrice.Text = price
tRow.Cells.Add(tCellPrice)
Dim tCellTotal As New TableCell()
tCellTotal.Text = total
tRow.Cells.Add(tCellTotal)
Dim tCellRemove As New TableCell()
tCellRemove.Text = "del!"
tRow.Cells.Add(tCellRemove)
Else
lblValidator.Visible = True
End If
End Sub

Just to clarify my comment above and show some code:
Dim tblRowColl As TableRowCollection = tblOrderPreview.Rows
'Run the code that gets the new row
For Each tblRow As TableRow In tblRowColl
tblOrderPreview.Rows.Add(tblRow)
Next
Hopefully this helps.
Thanks,
Firstcape

Related

If checkbox Checked then add to datatable from Gridview

I am trying check whether a checkbox is checked in a gridview and if it is checked to add it to the datatable.
However I am getting an error when the checkbox is unchecked for the row:
There is no row at position 1.
Here is my code:
'Creates a new datatable
Dim dtQuestions As New DataTable("QuestionsData")
'Add columns to datatable
For Each cell As TableCell In example.HeaderRow.Cells
dtQuestions.Columns.Add(cell.Text)
Next
For Each row As GridViewRow In example.Rows
Dim chkTest As CheckBox = CType(row.FindControl("chkTest"), CheckBox)
If chkTest.Checked = True Then
dtQuestions.Rows.Add()
For i As Integer = 0 To row.Cells.Count - 1
Try
dtQuestions.Rows(row.RowIndex)(i) = row.Cells(i).Text
Catch ex As Exception
End Try
Next
Else
'Do not add it to Datatable
End If
Next
I am getting the error on this code:
dtQuestions.Rows(row.RowIndex)(i) = row.Cells(i).Text
I do not know how to fix this.
If you want to add a row to a DataTable you should write this code
For Each row As GridViewRow In example.Rows
Dim chkTest As CheckBox = CType(row.FindControl("chkTest"), CheckBox)
If chkTest.Checked = True Then
Dim tableRow = dtQuestions.NewRow()
For i As Integer = 0 To row.Cells.Count - 1
tableRow(i) = row.Cells(i).Text
Next
dtQuestions.Rows.Add(tableRow)
End If
Next
Notice that I have removed the empty try/catch. Don't do it because it just hides your problems.

ASP Table doesnt save state

I created an ASP Table Control and added a row to it programatically. I then repeated the process to add another row. The first row that I added disappeared and only the newest row is being displayed. Is there a property that needs to be set to allow the state of the table to be saved?
EDIT:
All I do is click a button on the page and it adds a row to the table. Repeated clicks of the button only add one from to the table. If it helps, here is the function that adds the rows.
Protected Sub addItemButton(sender As Object, e As EventArgs)
'get the id of the item they selected
Dim id As String = CType(sender, Button).Text
'clear out the data being displayed
gridViewItemSearchItems.DataSource = Nothing
gridViewItemSearchItems.DataBind()
'add this item to the line table
Dim itemToAdd As Item = gp.Items.GetItemByKey(id)
Dim tableRow As New System.Web.UI.WebControls.TableRow()
Dim cellId As New System.Web.UI.WebControls.TableCell
cellId.Text = itemToAdd.Key.Id
Dim cellDesc As New System.Web.UI.WebControls.TableCell
cellDesc.Text = itemToAdd.Description
Dim cellMSRP As New System.Web.UI.WebControls.TableCell
cellMSRP.Text = gp.Items.GetItemMSRP(itemToAdd.Key)
Dim cellCost As New System.Web.UI.WebControls.TableCell
cellCost.Text = itemToAdd.CurrentCost.Value
Dim cellUnitPrice As New System.Web.UI.WebControls.TableCell
cellUnitPrice.Text = itemToAdd.StandardCost.Value
Dim cellDiscount As New System.Web.UI.WebControls.TableCell
cellDiscount.Text = "12%"
Dim cellQuantity As New System.Web.UI.WebControls.TableCell
cellQuantity.Text = "1"
tableRow.Cells.Add(cellId)
tableRow.Cells.Add(cellDesc)
tableRow.Cells.Add(cellMSRP)
tableRow.Cells.Add(cellCost)
tableRow.Cells.Add(cellUnitPrice)
tableRow.Cells.Add(cellDiscount)
tableRow.Cells.Add(cellQuantity)
tblItems.Rows.Add(tableRow)
End Sub
Since you're adding the rows to your table dynamically, they have to be re-created on each successive post-back.
Look at this answer for an explanation as to why dynamically added controls can disappear: ASP.NET dynamically created controls and Postback
EDIT: It is possible to dynamically add controls during a post-back, my answer here shows a way to do that using ViewState. Although, this does become very cumbersome. You might want to re-think the design of the page.

how do i display the "On Offer" indicator when the product is on offer in the database of asp.net?

I need to display the "on Offer" indicator next to the product in the gridview if the product has a number "1" in the "Offered" column in the database. if it is zero, then don't display. is there some way to achieve that? thanks.
In my product listing page:
Dim objCat As New Category
Dim objProduct As New Product
Dim i As Integer
Dim boolError As Boolean = False
objCat.ID = CType(Request.QueryString("CatID"), Integer)
' get details of the category
objCat.GetDetails()
' Display the category name
lblCatName.Text = objCat.Name
lblCatName2.Text = objCat.Name
' Display the category description
lblCatDesc.Text = objCat.Description
objCat.GetOfferedProducts()
For i = 0 To gvProduct.Rows.Count - 1
' Get the ProductId from the first cell
objProduct.ID = gvProduct.Rows(i).Cells(0).Text
Dim lblOffer As Label
lblOffer = CType(gvProduct.Rows(i).FindControl("lblOffer"), Label)
If objCat.Offered = "1" Then
lblOffer.Visible = True
Else
lblOffer.Visible = False
End If
Next
gvProduct.DataSource = objCat.GetProducts()
gvProduct.DataBind()
in my category class:
Public Sub GetOfferedProducts()
' Define a conection to database
' Read connection string from the web.config file.
Dim strConn As String
strConn = ConfigurationManager.ConnectionStrings("AppDb").ToString
Dim conn As New SqlConnection(strConn)
' Retrieve details of a given Category ID from the database
Dim strSql As String
strSql = "SELECT * FROM CatProduct cp INNER JOIN Product p " & _
"ON cp.ProductID=p.ProductID INNER JOIN Category c ON cp.CategoryID=c.CategoryID " & _
"WHERE cp.CategoryID=#CategoryID"
' Define an Command object to execute the SQL statement
Dim cmd As New SqlCommand(strSql, conn)
' Add parameter to the SQL command
cmd.Parameters.AddWithValue("#CategoryID", ID)
' Define a data adapter to fetch data
Dim da As New SqlDataAdapter(cmd)
' Define a data set to hold the data fetched
Dim ds As New DataSet
' Open database connection
conn.Open()
da.Fill(ds, "CatProduct")
' Close the database connection
conn.Close()
If ds.Tables("CatProduct").Rows.Count <> 0 Then
Name = ds.Tables("CatProduct").Rows(0)("CatName")
Description = ds.Tables("CatProduct").Rows(0)("CatDesc")
ImageFile = ds.Tables("CatProduct").Rows(0)("CatImage")
Offered = CType(ds.Tables("CatProduct").Rows(0)("Offered"), Integer)
End If
I would hook up the gridview's OnRowDataBound in your aspx page:
<asp:gridview id="MyGridView"
autogeneratecolumns="true"
allowpaging="true"
onrowdatabound="MyGridView_RowDataBound"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="lblOffer"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Then in the code behind you could do something like this:
void MyGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var lbl = e.Row.FindControl("lblOffer");
If objCat.Offered = "1" Then
lbl.Visible = True
Else
lbl.Visible = False
End If
}
}
Hope that helps!!
There are various ways to make this happen. Basically, you're just looking to conditionally show/hide an element in the grid.
Which of the many ways to do this happens to be the best way entirely depends on how you're retrieving, binding to and displaying your data. You can put the logic in the business layer (a certain property is set or null based on business rules, etc.), in your data binding code (if you're looping through records for the display or something, such as in an ItemDataBound handler), in your display code (if you're just declaring everything in the aspx and just need to toss in an Eval and a conditional), etc.

how to clear off gridview?

I'm creating a dynamic gridview function which will bind different tables from DB into a datatable and then assign the datatable to the gridview! This is how it works, i have a dropdownlist, gridview and a button, the button will fire specific function based on the dropdownlist selection and then gridview will bind the data, my problem is that, when u press the button for the 1st time, the gridview will bind the data from DB, for second time pressing, the gridview will duplicate the data from the data of 1st time pressing! how do i clear off the gridview to avoid data duplication?
Private Sub Login()
sSql = "" & _
"SELECT TYPE, SUBTYPE, LOGTS, ACTION, USERID, STAT1 " & _
"FROM i_LOG " & _
"WHERE TYPE = 'USR' AND SUBTYPE = 'LOG' " & _
"AND CONVERT(VARCHAR(20), LOGTS, 103) >= '" & txtDTFrom.Text & _
"' AND CONVERT(VARCHAR(20), LOGTS, 103) <= '" & txtDTTo.Text & "'"
DT = CreateDataTable(sSql) 'Retrieve from database.
Session(sSesDT) = DT
GVM.DataTable = DT
GVM.GVAddEmptyRow()
Dim seq As New BoundField
Dim Type As New BoundField
Dim SubType As New BoundField
Dim Logts As New BoundField
Dim action As New BoundField
Dim user As New BoundField
Dim status As New BoundField
seq.HeaderText = GVM.DTNumberField
seq.DataField = GVM.DTNumberField
Type.HeaderText = "Type"
Type.DataField = "TYPE"
SubType.HeaderText = "Subtype"
SubType.DataField = "SUBTYPE"
Logts.HeaderText = "Date and Time"
Logts.DataField = "LOGTS"
action.HeaderText = "Action"
action.DataField = "ACTION"
user.HeaderText = "User ID"
user.DataField = "USERID"
status.HeaderText = "Status"
status.DataField = "STAT1"
gv.AutoGenerateColumns = False
gv.Columns.Add(Type)
gv.Columns.Add(SubType)
gv.Columns.Add(Logts)
gv.Columns.Add(action)
gv.Columns.Add(user)
gv.Columns.Add(seq)
gv.Columns.Add(status)
gv.DataSource = Session(sSesDT)
gv.DataBind()
End Sub
Private Overloads Function CreateDataTable(ByVal sSql As String) As DataTable
Dim DA As New OleDb.OleDbDataAdapter
Dim dtDataTbl As New DataTable
Dim dcDataCol As New DataColumn
With DBMgr
.openCnn()
.SQL = sSql
.openRst()
DA.Fill(dtDataTbl, .rst)
End With
'==Adding Columns==
dcDataCol = New DataColumn 'No
With dcDataCol
.DataType = GetType(Int32)
.ColumnName = GVM.DTNumberField
.AutoIncrement = True
'.AllowDBNull = True
End With
dtDataTbl.Columns.Add(dcDataCol)
'**Adding Columns**
Return dtDataTbl
End Function
Sorry, this is in C#, but just call it before you bind any new data and it'll clear any existing data... unless of course the problem is that the DataSource you are assigning has the duplicated data.
gridview.DataSource=null;
gridview.DataBind();
Also, just to note, you are adding every column in every time that procedure is called? You need to run:
gridview.Columns.Clear();
You can reset it's data source and rebind it for example
gv.datasource=""
gv.databind()
and then reuse it
Usually this does not happen when you rebind grid like:
grid.DataSource = 'NEW_DATA_SOURCE'
grid.DataBind
I think may be the problem is in your function fetching data:
CreateDataTable(sSql)
Please check inside this if you are fetching data every time into a new DataTable or using same one (may be declared at global scope or passed from your class to data accessing component). I'd lost whole night once to fix this :(
Place your gridview in a table with an id:
<table id="myTable" border="0">
<tr><td>
<asp:GridView Width="765px" ID="mygrid" runat="server">
...
...
</asp:GridView>
</td></tr></table>
Then call from a button click your javascript function:
function clearGridview()
{
var rows = document.getElementById('myTable').getElementsByTagName('tbody') [0].getElementsByTagName('tr').length;
if(rows!=0)
document.getElementById("myTable").deleteRow(0);
}

Asp.net Grid View

In my Grid View ,When a button is clicked,i want to insert that row in to database and at the same time make the row invisible in the Grid View.
I can insert in to database but can't make the inserted row invisible.
Dim PayID As Integer = (e.CommandArgument)
Dim EmpID As Integer = (e.CommandArgument)
Dim EID As Integer = CType(Dg1.DataKeys(EmpID).Values("EmpID"), Integer)
Dim PID As Integer = CType(Dg1.DataKeys(PayID).Values("PayID"), Integer)
cmd.CommandText = "Insert into EmployDetails(EmpID,PayID,PayDate)
Values(" & EID & " ," & PID & ",GetDate())"
cmd.ExecuteNonQuery()
Thank You
You might need to bind the GridView to a DataView instead of a DataSet. Then when you add a row update the DataView to exclude the new row.
After insering your row to db, you should remove the related record from datasource (datatable, dataview) and rebind your gridview.
EDIT :
After your Insert operation :
1. take your remove the related row from your datasource :
Dim insertedRows As DataRow() = myDataTable.Select("ID = " & id)
For Each dr As DataRow In insertedRows
myDataTable.Rows.Remove(dr)
Next
2. And after that re-bind your gridview :
gridView.DataSource = myDataTable
gridView.DataBind()
NOTE : I use a converter to convert codes C# to VB. Hope it's ok.

Resources