Hey all i am wondering if it was possible to evaluate the datafield each time it places a new record into a row?
my gridview code is this:
<asp:Panel ID="pnlGrid" runat="server">
<div class="left_main_container" style="margin-bottom:20px;">
<asp:GridView ID="grdView" runat="server" CssClass="GridViewStyle"
AutoGenerateColumns="False" GridLines="None" Width="100%">
<Columns>
<asp:BoundField DataField="id" Visible="False" />
<asp:BoundField DataField="theName" HeaderText="Name" />
<asp:BoundField DataField="status" HeaderText="Status" />
</Columns>
<RowStyle CssClass="RowStyle" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedRowStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<EditRowStyle CssClass="EditRowStyle" />
<AlternatingRowStyle CssClass="AltRowStyle" />
</asp:GridView>
</div>
</asp:Panel>
The field i need to evaluate is status. I need to find out if the status is yes or if its no. If its no then i need to make it a link for the user to be able to change it to a yes.
The gridview is populated by this code:
Dim objConn As MySqlConnection
Dim objCmd As MySqlCommand
objConn = New MySqlConnection(strConnString)
objConn.Open()
Dim strSQL As String
strSQL = "SELECT id, status, " & _
"CONCAT(' ', first_name, last_name) AS theName " & _
"FROM(builder_requests) " & _
"ORDER BY status, id DESC;"
Dim dtReader As MySqlDataReader
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
grdView.DataSource = dtReader
grdView.DataBind()
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
Any help would be great!
I like to use a TemplateField and a function in your code-behind to do this sort of thing.
I am assuming your status field is a string field not boolean but if not let me know and I can adjust the example.
Replace your BoundField with...
Markup:
<asp:TemplateField>
<ItemTemplate>
<%# Eval("status")%>
<asp:LinkButton ID="cmdChangeStatus" runat="server" CommandName="ChangeStatusToYes" CommandArgument='<%# Eval("id") %>'
Visible='<%# SetChangeStatusVisibility(Eval("status")) %>'>Change to Yes</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
And add code behind function...
Code:
Protected Function SetChangeStatusVisibility(status As Object) As String
Dim strStatus As String = status.ToString()
If strStatus = "no" Then
Return "True"
Else
Return "False"
End If
End Function
Then you can handle the GridView.RowCommand event to change the status value based on the id value in CommandArgument :)
Related
I have a problem where I don't know how to combine between Facebox and OnselectedIndex function in asp.net.
Here is my code.
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" class="table table-bordered data-table" OnSelectedIndexChanged = "OnSelectedIndexChanged" >
<columns>
<asp:TemplateField HeaderText="No." ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<%# Container.DataItemIndex + 1%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Request ID" DataField="reqID"><ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:BoundField HeaderText="Username" DataField="reqName" />
<asp:BoundField HeaderText="Department" DataField="reqDept" />
<asp:BoundField HeaderText="Categories" DataField="reqCategories" />
<asp:BoundField HeaderText="Type" DataField="reqType" />
<asp:BoundField HeaderText="Description" DataField="reqDesc" />
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Action" itemstyle-horizontalalign="Center"><ItemTemplate><a runat="server" href="#info" rel="facebox" >More</a></ItemTemplate></asp:TemplateField>
</columns></asp:GridView>
Here is my facebox code :
<div id="info" style="display:none;">
<asp:GridView runat="server" ID="GridView2" AutoGenerateColumns="False" class="table table-bordered data-table">
<columns>
<asp:TemplateField HeaderText="No." ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<%# Container.DataItemIndex + 1%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Request ID" DataField="reqID" />
<asp:BoundField HeaderText="Verified By" DataField="verifiedBy" />
<asp:BoundField HeaderText="Verified Date" DataField="verifiedDate" />
<asp:BoundField HeaderText="Approved By" DataField="approvedBy" />
<asp:BoundField HeaderText="Approved Date" DataField="approvedDate" />
<asp:BoundField HeaderText="Accepted By" DataField="acceptedBy" />
<asp:BoundField HeaderText="Accepted Date" DataField="acceptedDate" />
<asp:BoundField HeaderText="Done By" DataField="doneBy" />
<asp:BoundField HeaderText="Done Date" DataField="doneDate" />
</columns></asp:GridView>
and here is my OnSelectedIndexChanged code :
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
Dim id As String
id = GridView1.SelectedRow.Cells(1).Text
conn.Open()
sqlstring = "SELECT * FROM ticketList where reqID = '" & id & "'"
cmd = New SqlCommand(sqlstring, conn)
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Close()
GridView2.DataSource = cmd.ExecuteReader
GridView2.DataBind()
End If
cmd.Dispose()
dr.Close()
conn.Close()
End Sub
Any idea when I click "More" then it will go to OnSelectedIndexChanged function and show data in my facebox?.
You need to add Handles GridView1.SelectedIndexChanged to the code:
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim id As String
id = GridView1.SelectedRow.Cells(1).Text
conn.Open()
sqlstring = "SELECT * FROM ticketList where reqID = '" & id & "'"
cmd = New SqlCommand(sqlstring, conn)
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Close()
GridView2.DataSource = cmd.ExecuteReader
GridView2.DataBind()
End If
cmd.Dispose()
dr.Close()
conn.Close()
End Sub
I have problem this gridview when I click on image button in gridview for delete row. I have this code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Username" HeaderText="Login Name">
<ItemStyle Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="Question" HeaderText="Question">
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="Answer" HeaderText="Answer">
<ItemStyle Width="150px" />
</asp:BoundField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False" AutoPostback = "True"
CommandName="Select" ImageUrl="~/images/trash.png" Text="Select" OnClientClick="return confirm('Do you want to delete?');" />
</ItemTemplate>
</asp:TemplateField>
when i click trash image for delete any row it gives me error. Invalid postback or callback argument.
This is my vb.net code
Private Sub updatedata(ByVal sql As String)
connectdb()
cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
conn.Close()
End Sub
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim sql4 As String = "delete from login WHERE username='" & GridView1.SelectedRow.Cells(0).Text.Trim() & "' "
updatedata(sql4)
I have checked all available articles and none seem to help me.
I have a GridView that is located inside a Repeater control. The data that populates the Gridview is dynamic and is grouped by a SectionID. I need for each repeated GridView to list the data rows grouped according to their SectionID.
How do I do this?
Thanks.
Here is what I have so far:
Public Sub GrabRepeaterData()
Dim connstr As String = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim ss As New SqlConnection(connstr)
Dim sqlStr As String = "SELECT SectionID, Name FROM Table1"
Dim selectCMD As New SqlClient.SqlCommand(sqlStr, ss)
Dim dt As New DataTable
Dim ds As New DataSet
Dim dataAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = selectCMD
dataAdapter.Fill(dt)
selectCMD.Dispose()
dataAdapter.Dispose()
ss.Close()
ss.Dispose()
dt.Columns.Add("Column1")
dt.Columns.Add("Column2")
dt.Columns.Add("Column3")
dt.Columns.Add("Column4")
dt.Columns.Add("Column5")
dt.Columns.Add("Column6")
dt.Columns.Add("Column7")
dt.Columns.Add("Column8")
For Each row As DataRow In dt.Rows
Dim SectionID As String = ""
SectionID = row("SectionID")
Dim Column1 As String = ""
Dim Column2 As String = ""
Dim Column3 As Boolean
Dim Column4 As String = ""
Dim Column5 As String = ""
Dim Column6 As String = ""
Dim Column7 As Boolean
Dim Column8 As Boolean
Dim ProgConn As String = ""
ProgConn = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim ProgSqlQuery As New SqlConnection(ProgConn)
Dim ProgResults As New SqlCommand("SELECT [Column1], [Column2], [Column3], [Column4], [Column5], [Column6], [Column7], [Column8] FROM Table2 WHERE SectionID = #SectionID ORDER BY Column4 DESC", ProgSqlQuery)
ProgResults.Parameters.AddWithValue("#SectionID", SectionID).Value = SectionID
ProgSqlQuery.Open()
Dim rProg As SqlDataReader = ProgResults.ExecuteReader()
While rProg.Read()
If Not rProg("Column1").Equals(DBNull.Value) Then
Column1 = CStr(rProg("Column1"))
End If
If Not rProg("Column2").Equals(DBNull.Value) Then
Column2 = CStr(rProg("Column2"))
End If
If Not rProg("Column3").Equals(DBNull.Value) Then
Column3 = CStr(rProg("Column3"))
End If
If Not rProg("Column4").Equals(DBNull.Value) Then
Column4 = CStr(rProg("Column4"))
End If
If Not rProg("Column5").Equals(DBNull.Value) Then
Column5 = CStr(rProg("Column5"))
End If
If Not rProg("Column6").Equals(DBNull.Value) Then
Column6 = CStr(rProg("Column6"))
End If
If Not rProg("Column7").Equals(DBNull.Value) Then
Column7 = CStr(rProg("Column7"))
End If
If Not rProg("Column8").Equals(DBNull.Value) Then
Column8 = CStr(rProg("Column8"))
End If
End While
rProg.Close()
ProgResults.Dispose()
ProgSqlQuery.Close()
ProgSqlQuery.Dispose()
row("Column1") = Column1
row("Column2") = Column2
row("Column3") = Column3
row("Column4") = Column4
row("Column5") = Column5
row("Column6") = Column6
row("Column7") = Column7
row("Column8") = Column8
row.EndEdit()
dt.AcceptChanges()
Next
CustomInfoRepeater.DataSource = dt
CustomInfoRepeater.DataBind()
End Sub
Protected Sub CustomInfoRepeater_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles CustomInfoRepeater.ItemDataBound
If e.Item.ItemType = ListItemType.Item Then
Try
Dim grdVw As GridView = TryCast(e.Item.FindControl("CustomInfoGridView"), GridView)
grdVw.DataSource = DirectCast(e.Item.DataItem, DataTable).Rows
grdVw.DataBind()
Dim CustPanel As UpdatePanel = DirectCast(CustomInfoRepeater.Items(0).FindControl("CustomInfoPanel"), UpdatePanel)
CustPanel.Update()
Catch
End Try
End If
End Sub
Here is my HTML:
<asp:Repeater ID="CustomInfoRepeater" runat="server">
<ItemTemplate>
<div class="download-box3">
</h2>
<asp:UpdatePanel ID="CustomInfoPanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="CustomInfoGridView" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="CustomInfoGridView" runat="server" Width="100%" AutoGenerateColumns="False"
DataKeyNames="Column1" GridLines="None" RowStyle-Height="40px" EnableViewState="False"
CellPadding="4" ForeColor="#333333" RowStyle-VerticalAlign="Middle">
<Columns>
<asp:BoundField DataField="Column1" />
<asp:TemplateField ItemStyle-Width="35px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:ImageButton ID="newIcon" runat="server" Width="31px" CssClass="myGridImage"
Visible="false" ImageUrl="images/new.png" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="35px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:ImageButton ID="DeleteButton" runat="server" AlternateText="Delete" ImageUrl="images/xmark.png"
OnClientClick="return confirm('Are you sure you want to delete this entry?')"
CommandArgument='<%# Eval("Column1") %>' CommandName="Remove" CssClass="myGridImage">
</asp:ImageButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="30px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:LinkButton ID="GenComUpdateButton" runat="server" CssClass="buttonsmall" Text="update"
CommandArgument='<%# Eval("Column1") %>' CommandName="GenComments"></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Impact" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="30px"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Image ID="statusIcon" runat="server" Width="20px" CssClass="myGridImage" Visible="false"
ImageUrl="" AlternateText="*" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="50px" HeaderText="Files" ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:ImageButton ID="filesIcon" runat="server" Width="23px" CssClass="myGridImage"
CommandArgument='<%# Eval("Column3") %>' CommandName="Download" Visible="false"
ImageUrl="images/pdf.png" AlternateText="*" />
<asp:LinkButton ID="AttachAssetsBtn" runat="server" CssClass="buttonredsmall" Text="upload"
CommandArgument='<%# Eval("Column1") %>' CommandName="Uploads" Visible="false"></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:BoundField DataField="Column3" HeaderText="Summary" HeaderStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle VerticalAlign="Middle" HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField ItemStyle-Width="50px" HeaderText="Reviewed" ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Image ID="reviewedIcon" runat="server" Width="23px" CssClass="myGridImage" Visible="false"
ImageUrl="images/checkmark.png" AlternateText="*" />
<asp:CheckBox ID="reviewedCheckBox" runat="server" CssClass="inputtext" Visible="false"
AutoPostBack="true" OnCheckedChanged="GenComCheckUpdate" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:BoundField DataField="Column4" HeaderText="Updated" HeaderStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle" ItemStyle-Width="75px">
<ItemStyle VerticalAlign="Middle" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Column6" Visible="false" />
<asp:BoundField DataField="Column7" Visible="false" />
</Columns>
<EmptyDataTemplate>
<span class="data-none">No Comments have been added to this section.</span>
</EmptyDataTemplate>
<RowStyle CssClass="RowStyle" BackColor="#F7F6F3" ForeColor="#333333" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
<PagerStyle CssClass="PagerStyle" BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle CssClass="SelectedRowStyle" BackColor="#E2DED6" Font-Bold="True"
ForeColor="#333333" />
<HeaderStyle CssClass="HeaderStyle" BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle CssClass="EditRowStyle" BackColor="#999999" />
<AlternatingRowStyle CssClass="AltRowStyle" BackColor="White" ForeColor="#284775" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</ItemTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:Repeater>
Thanks for your help!
What I understand from the code is you are merging two datasources into one. Then binding it to the Repeater and then fetching the datasource for GV from the repeater DataItem and binding it to the GridView.
What I would suggest is keep the datasources separate and do it in two steps:
1: Bind the repeater to just the SectionID i.e. data returned by SELECT SectionID, Name FROM Table1
2: In the Repeater ItemDataBound, get the SectionID and fetch data with the query you have in ProgResults. Then bind that to the GV.
I totally agree with gbs. Here's how you can do it:
In the markup, add a hidden field inside repeater, outside the updatepanel:
<asp:Repeater ID="CustomInfoRepeater" runat="server">
<ItemTemplate>
<asp:HiddenField ID="hdnSectionID" Value='<%# Eval("SectionID")%>' runat="server" />
<asp:Label ID="lblName" Text='<%# Eval("Name")%>' runat="server"></asp:Label>
<div class="download-box3">
</h2>
<asp:UpdatePanel ID="CustomInfoPanel" runat="server" UpdateMode="Conditional">
<%-- Rest of the markup goes here --%>
Rewrite GrabRepeaterData() sub only to populate the repeater:
Public Sub GrabRepeaterData()
Dim connstr As String = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim dt As New DataTable
Using conn As SqlConnection = New SqlConnection(connstr)
conn.Open()
Dim sqlStr As String = "SELECT SectionID, Name FROM Table1"
Dim cmd As New SqlClient.SqlCommand(sqlStr, conn)
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dt)
End Using
CustomInfoRepeater.DataSource = dt
CustomInfoRepeater.DataBind()
End Sub
In repeater's ItemDataBound, find the HiddenField, find it's value, find the GridView inside UpdatePanel, populate it this way:
Protected Sub CustomInfoRepeater_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles CustomInfoRepeater.ItemDataBound
If e.Item.ItemType = ListItemType.Item Then
Dim sectionID As Integer = 0
Dim hdnSectionID = TryCast(e.Item.FindControl("hdnSectionID"), HiddenField)
Dim CustomInfoPanel = TryCast(e.Item.FindControl("CustomInfoPanel"), UpdatePanel)
If (CustomInfoPanel IsNot Nothing AndAlso hdnSectionID IsNot Nothing AndAlso Integer.TryParse(hdnSectionID.Value, sectionID)) Then
Dim CustomInfoGridView = TryCast(CustomInfoPanel.FindControl("CustomInfoGridView"), GridView)
If (CustomInfoGridView IsNot Nothing) Then
Dim connstr As String = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim dt As New DataTable
Using conn As SqlConnection = New SqlConnection(connstr)
conn.Open()
Dim cmd As New SqlCommand("SELECT [Column1], [Column2], [Column3], [Column4], [Column5], [Column6], [Column7], [Column8] FROM Table2 WHERE SectionID = #SectionID ORDER BY Column4 DESC", conn)
cmd.Parameters.AddWithValue("#SectionID", sectionID)
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dt)
End Using
CustomInfoGridView.DataSource = dt
CustomInfoGridView.DataBind()
End If
End If
End If
End Sub
I keep getting the above error when trying to enter my value from a dropdownlist and my value from a GridViewRow.
It also says "Data Type Mismatch in Criteria Experession", I'm pulling the ID's of a Question and Paper from either the list/row and inputting them into my database.
Here's the code presenting the error.
Using con As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings.Item("ConnectionString").ConnectionString)
con.Open()
Dim allCheckedRows = From row In CreateTest.Rows.Cast(Of GridViewRow)()
Let chkQuestion = DirectCast(row.FindControl("QuestionSelector"), CheckBox)
Where chkQuestion.Checked
Select row
For Each checkedRow As GridViewRow In allCheckedRows
Dim QuestionID As String = (checkedRow.Cells(0).Text)
Dim PaperID As String = DropDownList1.SelectedValue
Dim insertExamQuery = "INSERT INTO QuestionInPaper VALUES ('QuestionID', 'PaperID');"
Dim insertExamCmd = con.CreateCommand()
insertExamCmd.CommandText = insertExamQuery
insertExamCmd.ExecuteNonQuery()
Next
End Using
Here's the aspx all of this refers to:
<asp:GridView ID="CreateTest" runat="server"
AllowSorting="True" AutoGenerateColumns="False" CellPadding="4"
DataKeyNames="QuestionID" DataSourceID="SqlDataSource1" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="QuestionSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="QuestionID" HeaderText="QuestionID"
InsertVisible="False" ReadOnly="True" SortExpression="QuestionID" />
<asp:BoundField DataField="Answer" HeaderText="Answer"
SortExpression="Answer" />
<asp:BoundField DataField="Question" HeaderText="Question"
SortExpression="Question" />
<asp:BoundField DataField="SubjectID" HeaderText="SubjectID"
SortExpression="SubjectID" />
<asp:TemplateField></asp:TemplateField>
</Columns>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [QuestionID], [Answer], [Question], [SubjectID] FROM [Question]">
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource3" DataTextField="PaperID" DataValueField="PaperID">
</asp:DropDownList>
Can you see where this mismatch is? ANy help is appreciated.
You are saying both your fields in QuestionInPaper are Numeric type, yet you are trying to insert string data - 'QuestionID' and 'PaperID'. You need to add them as parameters to your command. Also you are creating them as String, both types in code and database should be equal.
Using con As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings.Item("ConnectionString").ConnectionString)
con.Open()
Dim allCheckedRows = From row In CreateTest.Rows.Cast(Of GridViewRow)()
Let chkQuestion = DirectCast(row.FindControl("QuestionSelector"), CheckBox)
Where chkQuestion.Checked
Select row
For Each checkedRow As GridViewRow In allCheckedRows
'// change type and parse
Dim QuestionID As Decimal = Decimal.Parse(checkedRow.Cells(0).Text)
Dim PaperID As Decimal = Decimal.Parse(DropDownList1.SelectedValue)
'// changed
Dim insertExamQuery = "INSERT INTO QuestionInPaper (QuestionID, PaperID) VALUES (?, ?);"
Dim insertExamCmd = con.CreateCommand()
'// added below
insertExamCmd.Parameters.Add("#QuestionID", OleDb.OleDbType.Numeric).Value = QuestionID
insertExamCmd.Parameters.Add("#PaperID", OleDb.OleDbType.Numeric).Value = PaperID
'// end add
insertExamCmd.CommandText = insertExamQuery
insertExamCmd.ExecuteNonQuery()
Next
End Using
I have an editable gridview which the user can edit each row just by pressing linkbutton. I am getting an error and it stops my work. please help me.
HTML
<asp:GridView ID="gvList" runat="server" class="gv" CellPadding="2"
Font-Names="Calibri" ForeColor="#333333"
Font-Size="16px" Width="500px" AutoGenerateColumns="true" OnRowCancelingEdit="gvList_RowCancelingEdit"
OnRowEditing="gvList_RowEditing" OnRowUpdating="gvList_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="User Name" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true" ItemStyle-Width="170px">
<ItemTemplate>
<asp:Label runat="server" ID="lblUsername" Text='<%# Eval("cUserName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Editusername" runat="server" Text='<%# Eval("cUserName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept User" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true" ItemStyle-Width="170px">
<ItemTemplate>
<asp:Label runat="server" ID="lblDept" Text='<%# iif(Eval("lDeptUser"),"Yes","No") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" >
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true" ItemStyle-Width="160px">
<ItemTemplate>
<asp:LinkButton ID="btnedit" CommandName="Edit" runat="server" Text="Edit" />
<asp:LinkButton ID="btnDelete" CommandName="Delete" runat="server" Text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" CommandName="Update" runat="server" Text="Update" />
<asp:LinkButton ID="btnCancel" CommandName="Cancel" runat="server" Text="Cancel" />
</EditItemTemplate>
<HeaderStyle Font-Bold="True" ForeColor="White"></HeaderStyle>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No records available
</EmptyDataTemplate>
<HeaderStyle BackColor="#808380" Font-Bold="True" ForeColor="White" VerticalAlign="Top" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="#E3E3E3" />
</asp:GridView>
VB
Protected Sub gvList_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvList.RowUpdating
Dim oldname = DirectCast(gvList.Rows(e.RowIndex).FindControl("lblUsername"), Label)
Dim username As String = DirectCast(gvList.Rows(e.RowIndex).FindControl("Editusername"), TextBox).Text
Dim tempUser = DirectCast(gvList.Rows(e.RowIndex).FindControl("RadioButtonList1"), RadioButtonList).SelectedIndex
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname" +
",lDeptUser=#dept WHERE cUserName=#oldName"
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
con.Open()
Dim cmd = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#uname", username)
cmd.Parameters.AddWithValue("#dept", Convert.ToByte(tempUser))
cmd.Parameters.AddWithValue("#oldname", oldname)
cmd.ExecuteNonQuery()
End Using
gvList.EditIndex = -1
GetList()
End Sub
The problem is on the cmd.ExecuteNonQuery() it gives me The parameterized query '(#uname nvarchar(7),#dept tinyint,#oldname nvarchar(4000))Update' expects the parameter '#oldname', which was not supplied.
Any thing wrong in my query?
Try this
Dim oldname as Label =gvList.Rows(e.RowIndex).FindControl("lblUsername")
Dim username as TextBox = gvList.Rows(e.RowIndex).FindControl("Editusername")
Dim tempUser as RadioButtonList = DirectCast(gvList.Rows(e.RowIndex).FindControl("RadioButtonList1"), RadioButtonList).SelectedIndex
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname" +
",lDeptUser=#dept WHERE cUserName=#oldname"
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
con.Open()
Dim cmd = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#uname", username.Text)
cmd.Parameters.AddWithValue("#dept", Convert.ToByte(tempUser.SelectedIndex))
cmd.Parameters.AddWithValue("#oldname", oldname.Text)
cmd.ExecuteNonQuery()
End Using
you have change the parameter name by making "N" capital in #oldName,so due to that
you are getting that Error
there is a typo in your parameter
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname" +
",lDeptUser=#dept WHERE cUserName=#oldName"
And you have
cmd.Parameters.AddWithValue("#oldname", oldname)
isn't it should be
cmd.Parameters.AddWithValue("#oldName", oldname)
there is capital and small letter mistake.
Sorry I dont have enough rep to comment so I have to answer here...
Why are you casting label to label and trying to use it as string?:
Dim oldname as string = DirectCast(gvList.Rows(e.RowIndex).FindControl("lblUsername"), Label).text
seems more appropriate.
Im not sure about this but maybe because when you tried to hit the edit button and the gridview's mode is in edit mode the lblUsername label will be changed to Editusername textbox.. So what I suggest is you try to put a global variable string that will store the data of the lblUsername before updating or editing..
Try this
Code look fine, but this line command.commandtype = commandtype.text is missing may be that the problem.
Also while passing parameter Addwithvalue use username.text instead on username same for other controls too
Dim oldname As Label = DirectCast(gvList.Rows(e.RowIndex).FindControl("lblUsername"), Label)
Dim username As TextBox = DirectCast(gvList.Rows(e.RowIndex).FindControl("Editusername"), TextBox).Text
Dim tempUser As RadioButton = DirectCast(gvList.Rows(e.RowIndex).FindControl("RadioButtonList1"), RadioButtonList).SelectedIndex
Dim query As String = "Update Intranet.dbo.Gn_ISCoordinators SET cUserName=#uname, lDeptUser=#dept WHERE cUserName=#oldName"
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
con.Open()
Dim cmd = New SqlCommand(query, con)
cmd.commandtype = commandtype.text
cmd.Parameters.AddWithValue("#uname", username.text)
cmd.Parameters.AddWithValue("#dept", Convert.ToByte(tempUser.selectedvalue))
cmd.Parameters.AddWithValue("#oldname", oldname.text)
cmd.ExecuteNonQuery()
End Using
gvList.EditIndex = -1
GetList()