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
Related
I have a GridView I populate, and want to show/hide the edit link based on whether the person logged in is either an Admin or User. I am not receiving any errors but cannot figure out why its not working.
aspx
<asp:GridView ID="RepView" runat="server" HeaderStyle-BackColor="#bfbfbf" HeaderStyle-ForeColor="White" HeaderStyle-Font-Underline="true" CellPadding="2" GridLines="None" AutoGenerateColumns="false" Width="990px">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="EmployeeId" HeaderText="Employee Id" />
<asp:BoundField DataField="Shift" HeaderText="Shift" />
<asp:BoundField DataField="Supervisor" HeaderText="Supervisor" />
<asp:BoundField DataField="Center" HeaderText="Center" />
<asp:BoundField DataField="DateSubmitted" HeaderText="Date Entered" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Details">
<ItemTemplate>
Edit
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind
Private Sub BindGrid()
Dim DefaultConnection As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Using con As New SqlConnection(DefaultConnection)
'This is not working...
If My.User.IsInRole("User") Then
RepView.Columns(9).Visible = False
ElseIf My.User.IsInRole("Admin") Then
RepView.Columns(9).Visible = True
End If
' End of questionable part....
Using cmd As New SqlCommand()
cmd.CommandText = ("SELECT * from Reps")
cmd.Connection = con
con.Open()
RepView.DataSource = cmd.ExecuteReader()
RepView.DataBind()
con.Close()
End Using
End Using
End Sub
Try moving your code behind "Questionable Part" from the Private Sub BindGrid() to The gridview_Load event. My guess is that what's happening is that the gridview is loading, then it gets to your code Private sub BindGrid() to show/hide columns but the columns are already loaded, therefor it can not hide them. It will continue to show the columns even after running through this code unless you run the check and show/hide the columns in the load event.
One other possible solution is that it looks like in the Private Sub BindGrid() you are trying to hide the columns before the query which means the columns will not have been created yet so you have to create the columns first before you can hide and of them. Move the questionable part down below your sql command.
Try something like this...
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim x As Integer = 0
If x = 0 Then
GridView1.Columns(0).Visible = False
Else
GridView1.Columns(0).Visible = True
End If
End Sub
I have tested this and using x = 0 will hide the first column using x = 1 will show the first column.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Sprayer_Parts_CatalogConnectionString %>"
SelectCommand="SELECT [ID], [Order#] AS column1, [Gallon], [Price] FROM [Tanks]">
</asp:SqlDataSource>
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()
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 :)
I have the following gridview defined which is populating perfectly:
<asp:GridView runat="server" ID="chargeDetail" AutoGenerateColumns="false" DataKeyNames="LineItemNumber,DetailId,IsParking" CellSpacing="0" CellPadding="6"
HorizontalAlign="Center" EnableViewState="true" ShowFooter="true">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="StudentName" HeaderText="Name" ReadOnly="true" />
<asp:BoundField DataField="CampusName" HeaderText="Campus" ReadOnly="true" />
<asp:TemplateField HeaderText="Description" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="LineItemDetailLabel" Text='<%# IIf(Eval("Mandatory") = "1", Eval("LineItemDetail") + " *", Eval("LineItemDetail")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Cost" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
$<asp:Label runat="server" ID="LineItemCostLabel" Text='<%# Eval("LineItemCost") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="lblOptionsAvailable"
Text='<%# IIf(Eval("AttributesAvailable") = "1", "Options will be available to select on the next screen.", "No options available.") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pay Now" ItemStyle-HorizontalAlign="Center" FooterText="Total:">
<ItemTemplate>
<asp:Checkbox runat="server" ID="cbLineItemSelected" Checked='<%# IIf(Eval("Selected") = "1", "True", "False") %>'
Enabled='<%# IIf(Eval("Mandatory") = "1", "False", "True") %>' AutoPostBack="True" OnCheckedChanged="cbLineItemSelected_CheckedChanged" />
</ItemTemplate>
<FooterStyle Font-Bold="True" HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
$<asp:Label runat="server" ID="lblLineTotalCost" Text='<%# IIf(Eval("Selected") = "1", Eval("LineItemCost"), "0.00") %>' />
</ItemTemplate>
<FooterTemplate>
$<asp:Label runat="server" ID="lblTotal" />
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
</Columns>
</asp:GridView>
In the TemplateField where HeaderText="Options", I need to be able to create a variable number of drop-down lists. For each fee the school may be charging, they could have any number of attributes associated. For example, a TShirt fee may need to collect Size and Color and each attribute may have multiple options.
Right now, you can see I have a label that is populating correctly but I need to be able to create the two drop-down lists, in this case for Size and Color, so the parent can specify them when they check the box to include this fee in their charges. You'll notice that in the Pay Now column, the checkbox has an OnCheckedChanged event which currently updates the total column and overall total in the footer row.
I would ideally like that event to populate the drop-downs when it is checked so the parent can make their selections. I'll also need to know how to handle the post back from those drop-downs so I can get the selections recorded correctly.
From what I can find, I'm guessing I need to create a nested gridview where I can put the drop-downlists but I can't find any examples to point me in the right direction of how to make that work. I can easily populate the drop-downs from the code behind and if pointed in the right direction, access the data as the parents enter it. Just need a bit of direction or an easier way.
Thanks in advance!
OK, I came up with a solution that seems to work. Inside the gridview definition, I nested another gridview with the drop-down list inside of it as follows:
<asp:TemplateField HeaderText="Options" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:GridView runat="server" ID="gvOptions" AutoGenerateColumns="False" DataKeyNames="AttributeId" HorizontalAlign="center" EnableViewState="true"
GridLines="None" EmptyDataText="No available options." ShowHeader="False">
<Columns>
<asp:BoundField DataField="Description" ReadOnly="true" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlOptionSelection" DataTextField="Description" DataValueField="OptionId"
EnableViewState="true" AutoPostBack="true" OnSelectedIndexChanged="ddlOptionSelection_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
The challenge was figuring out how to tie everything together since data in the nested gridview relied on data keys from the parent gridview. The RowDataBound event for the parent finds the child gridview and populates the dropdowns as follows (gvOptions is the child and chargeDetail is the parent):
Protected Sub chargeDetail_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles chargeDetail.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim gv As GridView = DirectCast(e.Row.FindControl("gvOptions"), GridView)
Dim cb As CheckBox = DirectCast(e.Row.FindControl("cbLineItemSelected"), CheckBox)
Dim lineItem As String = chargeDetail.DataKeys(e.Row.RowIndex).Values("LineItemNumber")
gv.DataSource = GetOptions(chargeDetail.DataKeys(e.Row.RowIndex).Values("DetailId"))
gv.DataBind()
Dim gridLineCount As Integer = gv.Rows.Count()
Dim gridWorkingRow As Integer
For gridWorkingRow = 0 To gridLineCount - 1
Dim ddl As DropDownList = gv.Rows(gridWorkingRow).FindControl("ddlOptionSelection")
Dim AttribId As Integer = gv.DataKeys(gridWorkingRow).Values("AttributeId")
ddl.DataSource = PopulateOptions(AttribId)
ddl.DataBind()
ddl.SelectedValue = GetSelectedValue(AttribId, lineItem)
If cb.Checked Then
ddl.Enabled = True
Else
ddl.Enabled = False
End If
Next gridWorkingRow
End If
End Sub
When one of the dropdowns change, the following is fired. I found it easier, based on how the data is stored in the database, to re-send all of the options since the attribute:option pairs are concatenated to be stored in a single field:
Protected Sub ddlOptionSelection_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim ddlSender As DropDownList = DirectCast(sender, DropDownList)
Dim row As GridViewRow = DirectCast(ddlSender.NamingContainer, GridViewRow)
Dim gvOption As GridView = DirectCast(row.NamingContainer, GridView)
Dim chargeDetailRow As GridViewRow = DirectCast(gvOption.Parent.Parent, GridViewRow)
Dim LineItemNumber As Integer = CInt(chargeDetail.DataKeys(chargeDetailRow.RowIndex).Values("LineItemNumber"))
Dim gridLineCount As Integer = gvOption.Rows.Count()
Dim gridWorkingRow As Integer
Dim OptionString As String = ""
For gridWorkingRow = 0 To gridLineCount - 1
Dim ddl As DropDownList = gvOption.Rows(gridWorkingRow).FindControl("ddlOptionSelection")
Dim AttribId As String = gvOption.DataKeys(gridWorkingRow).Values("AttributeId")
If gridWorkingRow = gridLineCount - 1 Then
OptionString = OptionString + AttribId + ":" + ddl.SelectedValue
Else
OptionString = OptionString + AttribId + ":" + ddl.SelectedValue + ","
End If
Next gridWorkingRow
Dim PortalConn As New SqlConnection
PortalConn.ConnectionString = ConfigurationManager.ConnectionStrings("PortalConnStr").ConnectionString
PortalConn.Open()
Dim WriteBackSQL As New SqlCommand("sp_schedulePickup_UpdateOption", PortalConn)
WriteBackSQL.CommandType = Data.CommandType.StoredProcedure
WriteBackSQL.Parameters.Add(New SqlParameter("#SessionID", Session.SessionID.ToString()))
WriteBackSQL.Parameters.Add(New SqlParameter("#LineItemNumber", LineItemNumber))
WriteBackSQL.Parameters.Add(New SqlParameter("#Option", OptionString))
Dim returnStatus As Integer
Dim rsReturn As SqlDataReader = WriteBackSQL.ExecuteReader()
Do While rsReturn.Read()
returnStatus = rsReturn("ReturnStatus")
Loop
rsReturn.Close()
rsReturn = Nothing
PortalConn.Close()
PortalConn = Nothing
chargeDetail.DataSource = GetChargeDetails()
chargeDetail.DataBind()
getTotal()
End Sub
I'm trying to convert an empty string to null when editing a table in my gridview. I've tried several iterations and methods with no success. I'm suspecting that the issues is in my ObjectDataSource but don't know the correct syntax I need.
<asp:GridView
ID="grdMyDistributors"
DataSourceID = "srcGetMyDistributors"
CssClass="GridViewStyle"
DataKeyNames = "ID_Distributor"
AutoGenerateColumns = "false" AutoGenerateEditButton = "true"
GridLines="None"
runat="server" >
<Columns>
<asp:BoundField
DataField="DistributorName"
HeaderText="Distributor"
convertemptystringtonull="true"
ReadOnly = "True" />
<asp:BoundField
DataField="Distributor_Email_1"
HeaderText="Distributor Email 1"
convertemptystringtonull="true" >
<ItemStyle BackColor="#f6f17c"/>
</asp:BoundField>
<asp:BoundField
DataField="Distributor_Email_2"
HeaderText="Distributor Email 2"
convertemptystringtonull="true" >
<ItemStyle BackColor="#f6f17c"/>
</asp:BoundField>
<asp:BoundField
DataField="Minimum_Purchase_Amount"
HeaderText="Minimum Purchase Amount"
dataformatstring="{0:c}"
convertemptystringtonull="true" >
<ItemStyle BackColor="#f6f17c" />
</asp:BoundField>
</Columns>
</asp:GridView>
Here is my ObjectDataSource:
<asp:ObjectDataSource
ID="srcGetMyDistributors"
TypeName = "AAA.Distributors"
SelectMethod = "GetDistributorsPagingFiltered"
UpdateMethod = "UpdateDistributors"
EnableCaching="false"
ConvertNulltoDBNull = "true"
runat="server" >
<SelectParameters>
<asp:ProfileParameter Name="ID_Account" PropertyName="ID_Account" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter ControlID="grdMyDistributors" Name="ID_Distributor" PropertyName="SelectedValue" Type="Int32" />
</UpdateParameters>
</asp:ObjectDataSource>
Here is my update method
Public Shared Sub UpdateDistributors(ByVal ID_Distributor As Integer, ByVal Distributor_Email_1 As String, ByVal Distributor_Email_2 As String, ByVal Minimum_Purchase_Amount As Decimal)
' Initialize command
Dim con As New SqlConnection(_connectionString)
Dim cmd As New SqlCommand("UpdateDistributors", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con
' Initialize parameters
cmd.Parameters.AddWithValue("#ID_Distributor", A2AID_Restaurant_To_Distributor)
cmd.Parameters.AddWithValue("#Distributor_Email_1", Distributor_Email_1)
cmd.Parameters.AddWithValue("#Distributor_Email_2", Distributor_Email_2)
cmd.Parameters.AddWithValue("#Minimum_Purchase_Amount", Minimum_Purchase_Amount)
' Execute command
Using (con)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
When I run the code as is, I get an error saying "Object of type 'System.DBNull' cannot be converted to type 'System.String'." It's most likely erroring when it's trying to send to the Update method and expecting a string. If I take out "ConvertNulltoDBNull = "true" from the ObjectDataSource it complains that the SQL statement is expecting a value (meaning it's not sending the Null). I've tried so many variations of this and can't find any info in the class library. Any help would be greatly appreciated!
Thanks in advance!
use eval() for your gridview Columns
<%# Eval("DistributorName") == DBNull.Value ? "" : value.ToString()%>
(its in C#)
<asp:GridView
ID="grdMyDistributors"
DataSourceID = "srcGetMyDistributors"
CssClass="GridViewStyle"
DataKeyNames = "ID_Distributor"
AutoGenerateColumns = "false"
AutoGenerateEditButton = "true"
GridLines="None"
runat="server" >
<Columns>
<asp:TemplateField HeaderText="Seniority">
<ItemTemplate>
<%# Eval("DistributorName") == DBNull.Value ? "" :Eval("DistributorName").ToString()%>
</ItemTemplate>
</asp:TemplateField>
</Columns>