Convertemptystringtonull not working in gridview - asp.net

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>

Related

Stored procedure's parameter was not supplied in aspx.vb

I want to display data in a gridview using a SQL Server stored procedure. The interface should include two textboxes for two parameters, one button, and a gridview. The data will display after all parameters are filled out and the button is clicked. But I got an error saying
'Procedure or function 'uspGetBillOfMaterials' expects parameter '#StartProductID', which was not supplied.'
Edit 1: I found out that I called parameter StartProducID instead of StartProductID. Thank you guys for helping me with this. I fixed the problem.
Now I get a new error:
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Hope you can help me figure out where is my problem and the way to fix it.
Thanks.
Edit 2: I figured out my problems and posted the answer below. Basically, I just deleted the last two rows in my code-behind and it worked.
Here is my code in ASP.NET:
Please enter StartedProduct <asp:TextBox ID="StartProductID" runat="server"></asp:TextBox>
<br />
Please enter Date <asp:TextBox ID="CheckDate" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Search BOM" />
<br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="TestProc" AutoGenerateColumns="True">
<Columns>
<asp:BoundField DataField="ProductAssemblyID" HeaderText="ProductAssemblyID" ReadOnly="True" SortExpression="ProductAssemblyID" />
<asp:BoundField DataField="ComponentID" HeaderText="ComponentID" ReadOnly="True" SortExpression="ComponentID" />
<asp:BoundField DataField="ComponentDesc" HeaderText="ComponentDesc" ReadOnly="True" SortExpression="ComponentDesc" />
<asp:BoundField DataField="TotalQuantity" HeaderText="TotalQuantity" ReadOnly="True" SortExpression="TotalQuantity" />
<asp:BoundField DataField="StandardCost" HeaderText="StandardCost" ReadOnly="True" SortExpression="StandardCost" />
<asp:BoundField DataField="ListPrice" HeaderText="ListPrice" ReadOnly="True" SortExpression="ListPrice" />
<asp:BoundField DataField="BOMLevel" HeaderText="BOMLevel" ReadOnly="True" SortExpression="BOMLevel" />
<asp:BoundField DataField="RecursionLevel" HeaderText="RecursionLevel" ReadOnly="True" SortExpression="RecursionLevel" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="TestProc" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks2014ConnectionString %>"
SelectCommand="uspGetBillOfMaterials"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="StartProductID" Name="StartProductID" PropertyName="Text" Type="Int32" />
<asp:ControlParameter ControlID="CheckDate" Name="CheckDate" PropertyName="Text" Type="DateTime" />
</SelectParameters>
</asp:SqlDataSource>
Here is my code-behind:
Public Class TestStoredProcedure
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim command As New SqlCommand()
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
Dim connetionString As String = "Data Source=(local);Initial Catalog=AdventureWorks2014;Integrated Security=True"
Dim connection As New SqlConnection(connetionString)
connection.Open()
command.Connection = connection
command.CommandType = CommandType.StoredProcedure
command.CommandText = "uspGetBillOfMaterials"
command.Parameters.AddWithValue("StartProductID", StartProductID.Text)
command.Parameters.AddWithValue("#CheckDate", CheckDate.Text)
adapter = New SqlDataAdapter(command)
adapter.Fill(ds)
connection.Close()
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
End Sub
End Class
I figured out my problems:
The first error was because of a wrong parameter's name. It should be "StartProductID" instead of "StartProducID".
The second error was because I defined the gridview in both C# code and Vb code. I deleted the last two rows in my code-behind and it worked. Here is the link that helped me solve my issue.
Thank you all.

Reading data from a grid view into text boxes vb

I'm trying to read data retrieved into a gridview out to textboxes. My idea is to hide the gridview as im using it to retrieve data from a table that i need displayed in textboxes but i don't want the gridview to be shown.
So far i have tried this code:
Protected Sub btnFindRepair_Click(sender As Object, e As EventArgs) Handles btnFindRepair.Click
Dim row1 As GridViewRow = GridView1.SelectedRow
txtFname.Text = row1.Cells(3).Text
txtLname.Text = row1.Cells(4).Text
txtContactNum.Text = row1.Cells(5).Text
txtAltContactNum.Text = row1.Cells(6).Text
txtAddress.Text = row1.Cells(7).Text
End Sub
However this gives me the following error
An exception of type 'System.NullReferenceException' occurred in App_Web_lfjfpvke.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object
I have checked all of objects and instances and can't seem to find where the null value would come from
This is my gridview code
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2" DataKeyNames="Repair_ID">
<Columns>
<asp:BoundField DataField="Repair_ID" HeaderText="Repair_ID" SortExpression="Repair_ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="Booking_Number" HeaderText="Booking_Number" SortExpression="Booking_Number" Visible="False" />
<asp:BoundField DataField="Tracking_Number" HeaderText="Tracking_Number" SortExpression="Tracking_Number" Visible="False" />
<asp:BoundField DataField="First_Name" HeaderText="First_Name" SortExpression="First_Name" />
<asp:BoundField DataField="Last_Name" HeaderText="Last_Name" SortExpression="Last_Name" />
<asp:BoundField DataField="Contact_Number" HeaderText="Contact_Number" SortExpression="Contact_Number" />
<asp:BoundField DataField="Alternative_Contact_Number" HeaderText="Alternative_Contact_Number" SortExpression="Alternative_Contact_Number" />
<asp:BoundField DataField="Customer_Address" HeaderText="Customer_Address" SortExpression="Customer_Address" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Database %>" SelectCommand="SELECT * FROM [Customer] WHERE ([Tracking_Number] = #Tracking_Number)">
<SelectParameters>
<asp:ControlParameter ControlID="txtTrackingNumber" Name="Tracking_Number" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>

OlEdB Exception was unhandled by usercode

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

ASP.net gridview evaluating datafield after each record

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 :)

Getting SQLDataSource Update Parameter from Gridview

I am trying to get a parameter for my update from the gridview but it is an ID column that I do not want displayed. If I display the data in a boundfield it works fine but if I set the visibility to false the parameter is no longer sent to the update stored procedure. There does not appear to be a hiddenfield column that I can put into the gridview.
I have tried to set the parameters through the code behind but I am not certain on how to access the data I want the following code does not work (It sets the parameter to nothing
Protected Sub grvFacilityDisciplineBillingRate_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles grvFacilityDisciplineBillingRate.RowUpdating
Dim row As GridViewRow = grvFacilityDisciplineBillingRate.Rows(e.RowIndex)
sqlDisciplineBillingRate.UpdateParameters("Facility_ID").DefaultValue = CInt(row.DataItem("Facility_ID"))
sqlDisciplineBillingRate.UpdateParameters("Discipline_ID").DefaultValue = CInt(row.DataItem("Discipline_ID"))
End Sub
And this is the front end with the two ID columns displayed, which is not what I want
<asp:SqlDataSource ID="sqlDisciplineBillingRate" runat="server" DataSourceMode="DataSet" SelectCommandType="StoredProcedure" SelectCommand="SP_Facility_DisciplineBillingRates" UpdateCommandType="StoredProcedure" UpdateCommand="SP_DiscplineBillingRate_Update" ConnectionString="<%$ ConnectionStrings:Trustaff_ESig2 %>">
<SelectParameters>
<asp:Parameter Name="Facility_ID" DbType="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Facility_ID" DbType="Int32" />
<asp:Parameter Name="Discipline_ID" DbType="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView ID="grvFacilityDisciplineBillingRate" runat="server" DataSourceID="sqlDisciplineBillingRate" DataKeyNames="DisciplineBillingRate_ID" AutoGenerateColumns="false" AllowSorting="true" AllowPaging="false" AutoGenerateEditButton="true" CssClass="gridview">
<EmptyDataTemplate>
There were no discipline billing rates for this facility.
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="Name" HeaderText="Discipline" SortExpression="Name" ReadOnly="true" />
<asp:BoundField DataField="BillingRate" HeaderText="Billing Rate" SortExpression="BillingRate" />
<asp:BoundField DataField="Facility_ID" HeaderText="Facility_ID" SortExpression="Facility_ID" InsertVisible="false" />
<asp:BoundField DataField="Discipline_ID" HeaderText="Discipline_ID" SortExpression="Discipline_ID" />
</Columns>
</asp:GridView>
You simply have to set the DataKeyNames e.g. DataKeyNames="Facility_ID,Discipline_ID" and the SqlDataSource will figure it out for you when using GV's Update and Delete feature.
Try using Template fields and use a label control and hide them by setting visible="false".
<asp:TemplateField HeaderText="College">
<ItemTemplate>
<asp:Label ID="lbl_Title" runat="server" text='<%# Bind("Title") %>' visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And use below code to access values from codebehind.
If gvrow.RowType = DataControlRowType.DataRow Then
Dim label1 As Label = DirectCast(gvrow.FindControl("lbl_Title"), Label)
'Access text of label using label1.text and cast to int or string
End If
You can eliminate using templated fields if you don't wish for ID columns. And still access it using datakeynames property

Resources