If checkbox Checked then add to datatable from Gridview - asp.net

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.

Related

Change Grid view value based on some condition

I have a Grid view control with a few columns that is populated from a form that the user fills in. In the form some values are not mandatory and if the user does not select them, then it is displayed as "select" in the Grid view. How do i go about changing that value to something for relative like "none" when i load the Grid view. In other words , if that column contains "select" then change it to "None"
This is my code behind to populate my Gridview
Private Sub LoadGridAll()
txtSearchEmployee.Text = ""
Try
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("XXX").ConnectionString)
Using cmd As New SqlCommand("SELECT EmployeeCodes.Code, EmployeeCodes.FirstName , EmployeeCodes.LastName , EmployeeCodes.EmployeeID , CostCentre , ExaminationType.ExaminationTypeName , PhysicalExam.PhysicalExamName , ExaminationType.ExaminationTypeName , PhysicalExam.PhysicalExamName , Audiogram.AudiogramName , AudiogramRec.AudiogramRecName,LungFunction.LungFunctionName,ChestResults,ECGResult,DrugScreeningResult,BloodGlucoseResult,GGTResult,LeftEyeDayNight,RightEyeDayNight,LeftEyeCorrDayNight,RightEyeCorrDayNight,VisualFieldLeftDayNight,VisualFieldRightDayNight,ColourVisionDayNight,DeptPerceptionDayNight,OptometristYesNo,Outcome.Name , OutcomeRecommendations.OutcomeRecommendationsName,OtherProblems,Notes,DateTested,NextDueDate FROM MedicalResults,EmployeeCodes,ExaminationType,PhysicalExam,Audiogram,AudiogramRec,LungFunction,Outcome,OutcomeRecommendations WHERE MedicalResults.EmployeeID = EmployeeCodes.EmployeeID AND ExaminationType.ExaminationTypeID = MedicalResults.ExaminationTypeID AND PhysicalExam.PhysicalExamID = MedicalResults.PhysicalExamType AND Audiogram.AudiogramID = MedicalResults.AudiogramID AND MedicalResults.AudiogramRecID = AudiogramRec.AudiogramRecID AND LungFunction.LungFunctionID = MedicalResults.LungFunctionID AND OutcomeRecommendations.OutcomeRecommendationsID = MedicalResults.OutcomeRecommendationsID AND Outcome.OutcomeID = MedicalResults.OutcomeID ", conn)
conn.Open()
Dim sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
For Each row As DataRow In dt.Rows
Dim strDetail As Object
strDetail = row.Item(10)
If strDetail = "Select" Then
strDetail = "None"
End If
Next row
GridViewAll.DataSource = dt
GridViewAll.DataBind()
conn.Close()
End Using
End Using
Catch ex As Exception
End Try
End Sub
First of all, I wouldn't save "Select" to DB, it would make more sense to save a null value (DBNull.Value). Then in your select statement you could use a function IsNull(yourField,'None'). Edit: if you have Null values in grid, you could also use DataGridView's property:
Me.GridViewAll.RowsDefaultCellStyle.NullValue = "None"
However, if you want to do it like you've shown, you're very close - you just need to save the new String value to DataTable:
row.Item(10) = "None" 'strDetail

Dynamically add checkbox to ASP.NET table row

I am trying to add a checkboxlist and then add a new checkbox to every row in an ASP.NET table:
Dim cbList As New CheckBoxList
cbList.ID = "cb_list"
Dim c1 As New TableCell
Dim c2 As New TableCell
Dim r As New TableRow
c1.Controls.Add(New LiteralControl(dr.GetString(1)))
c2.Controls.Add(cbList.Items.Add("new cb")) 'error: expression does return a value
r.Cells.Add(c1)
r.Cells.Add(c2)
modaltable.Rows.Add(r)
The c2.Controls line returns the following error:
"expression does return a value"
I can't seem to get round this problem. Any help is appreciated!

How to compare row values of two gridviews with dropdownlist column in asp.net?

I have two gridviews. The first one has a dropdownlist. When a user clicks a button named 'Show' data will be displayed on both gridviews where data comes from database. The row data on column with dropdownlist must be compared to the rows on the first column of the second gridview. If they are equal a messagebox will prompt saying that there's no changes and data will not be saved, else if they are not equal modal pop-up will be displayed asking if data are correct.
Below is my code for comparing but it only reads the value of the 1st row in gridview1.
For i = 0 To GridView1.Rows.Count - 1
Dim ddl As DropDownList = DirectCast(GridView1.Rows(i).Cells(6).FindControl("dropdowncriteria"), DropDownList)
Dim txt As TextBox = DirectCast(GridView1.Rows(i).Cells(7).FindControl("txtreason"), TextBox)
If ddl.SelectedValue = GridView2.Rows(i).Cells(0).Text And txt.Text = GridView2.Rows(i).Cells(1).Text Then
MessageBox("No Changes Made! Nothing will be Saved.")
Return
Else
lblmsg.Text = "Are you sure that all the Data you've Selected/Entered are Correct?"
mdlpopupmsg.Show()
Return
End If
Next
What must be the problem on this?
Thanks in advance.
It only reads the first value (i=0) because the return statements cause the for loop to exit after the first comparison. If you want to compare all the rows you will need a variable to keep track of the result of the if test for each row. Something like this:
Dim hasChanges As Boolean = False
For i = 0 To GridView1.Rows.Count - 1
...
If ddl.SelectedValue = GridView2.Rows(i).Cells(0).Text And txt.Text = GridView2.Rows(i).Cells(1).Text Then
'do nothing
Else
hasChanges = True
End If
Next
If hasChanges Then
MessageBox("Has changes.")
Else
MessageBox("No changes.")
End If
Dim itemt As Double
If (DataGridCart.RowCount() > 0) Then
For i = 0 To DataGridCart.Rows.Count - 1
'if itemt as double
itemt = Val(Trim(txtItem.Text))
If ((DataGridCart.Rows(i).Cells("Item").Value).Equals(itemt)) Then
MsgBox("existing entry")
End If
Next
End If

Table Rows Disappear on Dropdown ItemSelected

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

define checkboxes as checked in checkboxlist

I can't figure out how to set the "checked" value of certain checkboxes in a checkboxlist during page load. So far I have this, but it doesn't work.
For Each DataRow As DataRow In groupDataset().Tables(0).Rows
Dim i As Integer
For i = 0 To cblGroups.Items.Count - 1
Response.Write(cblGroups.DataValueField)
If DataRow("memberID").ToString = cblGroups.DataValueField Then
cblGroups.Items(i).Selected = True
End If
Next
Next
Is this even possible?
Thanks
Try this. You need to look at each item in the checkboxlist, not the datavaluefield of the group itself.
For Each DataRow As DataRow In groupDataset().Tables(0).Rows
Dim i As Integer
For i = 0 To cblGroups.Items.Count - 1
Response.Write(cblGroups.Items(i).Value)
If DataRow("memberID").ToString = cblGroups.Items(i).Value Then
cblGroups.Items(i).Selected = True
End If
Next
Next

Resources