SqlDataSource InsertCommand Missing Required Parameters - c#

I keep getting an OleDbException :"No value given for one or more required parameters" - Not very specific.
I have had no luck finding a solution to my problem online. I have tried many different things like not declaring the Parameters in the form and creating them at run time in the code behind.
Here is my ugly code:
<asp:sqldatasource ID="datasource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [ID], [Test Data] AS Test_Data, [More Data] AS More_Data FROM [Main]"
UpdateCommand="UPDATE [Main] SET [Test Data]=#TestData, [More Data]=#MoreData WHERE [ID]=#ID"
InsertCommand="INSERT INTO [Main] ([ID], [Test Data], [More Data]) VALUES (#InsertID, #InsertTestData, #InsertMoreData)"
DeleteCommand="" >
<UpdateParameters>
<asp:ControlParameter Name="TestData" ControlId="updateTest" PropertyName="Text" />
<asp:ControlParameter Name="MoreData" ControlId="updateMore" PropertyName="Text" />
<asp:ControlParameter Name="InsertTestData" ControlId="insertTest" PropertyName="Text" />
<asp:ControlParameter Name="InsertID" ControlId="insertIDD" PropertyName="SelectedValue" />
<asp:ControlParameter Name="InsertMoreData" ControlId="insertMore" PropertyName="Text" />
<asp:ControlParameter Name="ID" ControlId="DropDownList2" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:sqldatasource>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true" DataSourceID="datasource"></asp:GridView>
<br />
<asp:DropDownList ID="insertIDD" DataSourceID="datasource" DataTextField="ID" runat="server" Font-Bold="False"></asp:DropDownList>
<asp:TextBox ID="insertTest" runat="server"></asp:TextBox>
<asp:TextBox ID="insertMore" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Insert" />
<br />
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="datasource" DataTextField="ID" OnTextChanged="populateDrop" AutoPostBack="true"></asp:DropDownList>
<asp:TextBox ID="updateTest" runat="server"></asp:TextBox>
<asp:TextBox ID="updateMore" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Update" OnClick="Update" />
<br />
<asp:Button ID="Button3" runat="server" Text="Delete" OnClick="Delete" />**
And the C# Code Behind:
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
DataView dv = new DataView();
protected void Page_Load(object sender, EventArgs e)
{
dv = (DataView)datasource.Select(DataSourceSelectArguments.Empty);
updateTest.Text = dv[0]["Test_Data"].ToString();
updateMore.Text = dv[0]["More_Data"].ToString();
}
protected void Insert(object sender, EventArgs e)
{
datasource.Insert();
}
protected void Update(object sender, EventArgs e)
{
datasource.Update();
updateTest.Text = "";
updateMore.Text = "";
}
SELECT and UPDATE work without any problem. No matter what I try I cannot get the INSERT INTO command to be happy. I am sure it is something simple that I am missing, but any help would be greatly appreciated, thanks!

this is for Update:
<UpdateParameters>
<asp:ControlParameter Name="TestData" ControlId="updateTest" PropertyName="Text" />
<asp:ControlParameter Name="MoreData" ControlId="updateMore" PropertyName="Text" />
<asp:ControlParameter Name="ID" ControlId="DropDownList2" PropertyName="SelectedValue" />
</UpdateParameters>
and this is for Insert
<InsertParameters>
<asp:ControlParameter Name="InsertTestData" ControlId="insertTest" PropertyName="Text" />
<asp:ControlParameter Name="InsertID" ControlId="insertIDD" PropertyName="SelectedValue" />
<asp:ControlParameter Name="InsertMoreData" ControlId="insertMore" PropertyName="Text" />
</InsertParameters>
At the end:
<asp:sqldatasource ID="datasource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [ID], [Test Data] AS Test_Data, [More Data] AS More_Data FROM [Main]"
UpdateCommand="UPDATE [Main] SET [Test Data]=#TestData, [More Data]=#MoreData WHERE [ID]=#ID"
InsertCommand="INSERT INTO [Main] ([ID], [Test Data], [More Data]) VALUES (#InsertID, #InsertTestData, #InsertMoreData)"
DeleteCommand="" >
<UpdateParameters>
<asp:ControlParameter Name="TestData" ControlId="updateTest" PropertyName="Text" />
<asp:ControlParameter Name="MoreData" ControlId="updateMore" PropertyName="Text" />
<asp:ControlParameter Name="ID" ControlId="DropDownList2" PropertyName="SelectedValue" />
</UpdateParameters>
<InsertParameters>
<asp:ControlParameter Name="InsertTestData" ControlId="insertTest" PropertyName="Text" />
<asp:ControlParameter Name="InsertID" ControlId="insertIDD" PropertyName="SelectedValue" />
<asp:ControlParameter Name="InsertMoreData" ControlId="insertMore" PropertyName="Text" />
</InsertParameters>
</asp:sqldatasource>

Related

ASP.NET label in HTML accessDataSource

I need to replace the ? with lblDates.Text,how is that possible?? lblDates is a label to which I saved a date(string) from calendar,so I need this so I can fill the gridview
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_data/Baza1.accdb"
SelectCommand="SELECT [Spol], [Prezime], [Vrijeme], [Stol] FROM [rezervacije] WHERE ([Datum] = ?)">
<SelectParameters>
<asp:ControlParameter ControlID="lblDates" Name="Datum" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:AccessDataSource
Since the ControlParameter that retrieves lblDates.Text has Name="Datum", replace ? in SelectCommand with #Datum:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_data/Baza1.accdb"
SelectCommand="SELECT [Spol], [Prezime], [Vrijeme], [Stol] FROM [rezervacije] WHERE ([Datum] = #Datum)">
<SelectParameters>
<asp:ControlParameter ControlID="lblDates" Name="Datum" PropertyName="Text"
Type="String" />
</SelectParameters>
</asp:AccessDataSource>
For more information, see Using Parameters with Data Source Controls.

Inserting into SQL Server database ASP.net

What I'm trying to do is to insert a username, and their monthly hour limit to my SQL Server database. I've used the automatically generated statements for updating and deleting. I just need to add in new users now. The code below, should work as far as I know, but it doesn't. I think it's the way I've written it.
The part in comments is what the Userdata.aspx file automatically generated, so I'm trying to convert it to use my 2 text boxes.
Thanks a lot.
protected void Button1_Click1(object sender, EventArgs e)
{
string sql = "INSERT INTO [UserData]([UserName], [MonthlyHourLimit]) VALUES ("+ TextBox1.Text + "," + TextBox2.Text + ")";
//INSERT INTO [UserData] ([UserName], [MonthlyHourLimit]) VALUES (#UserName, #MonthlyHourLimit)"
SqlDataSource1.InsertCommand = sql;
GridView1.DataBind();
}
You need to configure your data source to use parameters.
<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"
SelectCommand="select [UserName], [MonthlyHourLimit] from [UserData] where UserName= #UserName"
InsertCommand="IINSERT INTO [UserData] ([UserName], [MonthlyHourLimit]) VALUES (#UserName, #MonthlyHourLimit);"
ConnectionString="<%$ ConnectionStrings:MyConnection %>"
RunAt="server">
<SelectParameters>
<asp:Parameter Name="UserName" Type="Int32" DefaultValue="0" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="UserName" Direction="Input" Type="String" />
<asp:Parameter Name="MonthlyHourLimit" Direction="Input" Type="String" />
</InsertParameters>
</asp:sqlDataSource>
UPDATE:I've forgot to mention, you would like to use ControlParameter and not simple Parameter. Take a look at following snippet:
<asp:СontrolParameter Name="UserName" ControlId="ddlUserNames" PropertyName="SelectedValue"/>
...
<asp:DropdownList
ID="ddlUserNames"
runat="server"
Autopostback="True">
<asp:Listitem Selected="True">Users</asp:Listitem>
<asp:Listitem Value="Peter">Peter</asp:Listitem>
<asp:Listitem Value="Jessica">Jessica</asp:Listitem>
</asp:Dropdownlist>
Take a look at corresponding MSDN page describing usage of SqlDataSource in details.
UPDATED 2: complete example in order to avoid confusion
<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"
SelectCommand="select [UserName], [MonthlyHourLimit] from [UserData] where UserName= #UserName"
InsertCommand="IINSERT INTO [UserData] ([UserName], [MonthlyHourLimit]) VALUES (#UserName, #MonthlyHourLimit);"
ConnectionString="<%$ ConnectionStrings:MyConnection %>"
RunAt="server">
<SelectParameters>
<asp:Parameter Name="UserName" Type="Int32" DefaultValue="0" />
</SelectParameters>
<InsertParameters>
<asp:ControlParameter Name="UserName" ControlId="txtUserName" Direction="Input" Type="String" />
<asp:ControlParameter Name="MonthlyHourLimit" ControlId="txtMonthlyHourLimit" Direction="Input" Type="String" />
</InsertParameters>
</asp:sqlDataSource>
<asp:TextBox runat="server" ID="txtUserName" />
<asp:TextBox runat="server" ID="txtMonthlyHourLimit" />
Datasource.InsertCommand is a property.
Datasource.Insert() is a method.
You should also use parameters.
datasource.insertparameters("username").defaultvalue = TextBox1.Text + "," + TextBox2.Text

Insert proper phone format

I have a textbox which stores phone number.
<asp:TextBox runat="server" ID="phone" MaxLength="10" Columns="10" Width="90px" />
<asp:MaskedEditExtender ID="phone_MaskedEditExtender" runat="server" CultureAMPMPlaceholder=""
CultureCurrencySymbolPlaceholder="" CultureDateFormat="" CultureDatePlaceholder=""
CultureDecimalPlaceholder="" CultureThousandsPlaceholder="" CultureTimePlaceholder=""
Enabled="True" TargetControlID="phone" Mask="(999)-999-9999" ClearMaskOnLostFocus="False">
</asp:MaskedEditExtender>
The question is when I insert phone number 9999999999, the number in the database becomes
(999)-9999.
What I want is 9999999999.
The other code is:
<asp:SqlDataSource ID="InsertExtraInfo" runat="server" ConnectionString="<%$ ConnectionStrings:MembershipDB %>"
InsertCommand="CreateAdditionalAccountInfo" InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:ControlParameter Name="FirstName" Type="String" ControlID="FirstName" PropertyName="Text" />
<asp:ControlParameter Name="LastName" Type="String" ControlID="LastName" PropertyName="Text" />
<asp:ControlParameter Name="Degree" Type="String" ControlID="Degree" PropertyName="Text" />
<asp:ControlParameter Name="Organization" Type="String" ControlID="Organization"
PropertyName="Text" />
<asp:ControlParameter Name="Phone" Type="String" ControlID="Phone" PropertyName="Text" />
<asp:ControlParameter Name="Ext" Type="String" ControlID="Ext" PropertyName="Text" />
<asp:ControlParameter Name="last4SSN" Type="String" ControlID="TextSSN" PropertyName="Text" />
</InsertParameters>
</asp:SqlDataSource>
The stored Procedure query is
INSERT INTO [User_ExtraInfo] ([UserId], [FirstName], [LastName], [Degree], [Organization], [Phone], [Ext], [last4SSN],[Trained]) VALUES (#UserId, #FirstName, #LastName, #Degree, #Organization, #Phone, #Ext
Thanks.
Change the proc to this:
INSERT INTO [User_ExtraInfo] ([UserId], [FirstName], [LastName], [Degree], [Organization], [Phone], [Ext], [last4SSN],[Trained]) VALUES (#UserId
, #FirstName
, #LastName
, #Degree
, #Organization
, REPLACE(REPLACE( REPLACE(#Phone,'(',''),')','') ,'-','') , #Ext )
The reason I suggest this approach is because you are using a SQLDatasource object and I don't think it's possible to instruct the insert parameter -at least not declaratively from the markup- to ignore the mask. Your best bet is probably just to modify the proc.
UPDATE - programmatic approach:
Add a handler for OnInserting to the SqlDataSource:
<asp:SqlDataSource ID="InsertExtraInfo" runat="server" OnInserting="On_Inserting"
Handle the event on code and do the replacement there:
protected void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e) {
e.Command.Parameters["#Phone"].Value=phone.Text.Replace("..."); // etc
}
Note: not tested but it's the idea.

How to retrieve data from the database to the second table after selecting the user in the first table?

I have three tables in my database as following:
Employee Table: Username, Name, Job, DivisonCode
Course Table: CourseID, CourseName, GroupID
Employee_Course Table: Username, CourseID (The first key in each table is the primary key)
I created two ListViews; one for retrieving the employee information from the Employee Table and the second one to show the taken courses (from Employee_Course Table) of the selected employee in the first ListView.
For the first table, everything works well and fine, but for the second table, I could not be able to retrieve the taken courses of the selected employee in the first table.
So how can I do that?
My ASP.NET code:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Username"
DataSourceID="SqlDataSource1" InsertItemPosition="LastItem">
<EditItemTemplate>
<tr style="">
<td>
<asp:ImageButton ID="UpdateButton" ImageUrl="images/update4.png" Width="20px" runat="server" CommandName="Update" />
<asp:ImageButton ID="CancelButton" ImageUrl="images/cancel.png" Width="20px" runat="server" CommandName="Cancel" />
</td>
<td>
<asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
</td>
<td>
<asp:Label ID="UsernameLabel1" runat="server" Text='<%# Eval("Username") %>' />
</td>
<td>
<asp:TextBox ID="JobTitleTextBox" runat="server"
Text='<%# Bind("JobTitle") %>' />
</td>
<td>
<asp:TextBox ID="BadgeNoTextBox" runat="server" Text='<%# Bind("BadgeNo") %>' />
</td>
<td>
<asp:TextBox ID="EmpOrgTypeTextBox" runat="server"
Text='<%# Bind("EmpOrgType") %>' />
</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("DivisionCode") %>'
DataSourceID="SqlDataSource1" DataTextField="DivisionName"
DataValueField="SapCode">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
DeleteCommand="DELETE FROM [Divisions] WHERE [SapCode] = #SapCode"
InsertCommand="INSERT INTO [Divisions] ([SapCode], [DivisionName]) VALUES (#SapCode, #DivisionName)"
SelectCommand="SELECT * FROM [Divisions]"
UpdateCommand="UPDATE [Divisions] SET [DivisionName] = #DivisionName WHERE [SapCode] = #SapCode">
<DeleteParameters>
<asp:Parameter Name="SapCode" Type="Double" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="SapCode" Type="Double" />
<asp:Parameter Name="DivisionName" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="DivisionName" Type="String" />
<asp:Parameter Name="SapCode" Type="Double" />
</UpdateParameters>
</asp:SqlDataSource>
</td>
</tr>
</EditItemTemplate>
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>
No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
DeleteCommand="DELETE FROM [employee_courses] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [employee_courses] ([employeeId], [courseId]) VALUES (#employeeId, #courseId)"
SelectCommand="SELECT * FROM [employee_courses] WHERE ([employeeId] = #Username)"
UpdateCommand="UPDATE [employee_courses] SET [employeeId] = #employeeId, [courseId] = #courseId WHERE [ID] = #ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="employeeId" Type="String" />
<asp:Parameter Name="courseId" Type="Int32" />
<asp:ControlParameter ControlID="ListView1" Name="Username" PropertyName="SelectedValue" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:ControlParameter ControlID="ListView1" Name="Username"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
<UpdateParameters>
<%--<asp:Parameter Name="employeeId" Type="String" />--%>
<asp:Parameter Name="courseId" Type="Int32" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
First of all you have to get data from database. You can connect to your database through System.Data.SqlClient libraries. Then fill your listview with those data: example.
ListView from msdn.
If you want to learn programming in asp.net you can check book from wrox Beginning ASP.NET 4 in C#
For example
databinding looks like
//YourWebForm1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
DataSet dataSet = GetYourDataFromDBMethode() // methode gets data from dataset like in msdn spec which I posted above in example;
ListView1.DataSource = dataSet;
ListView.DataBind();
}
Then on SelectedIndexChanged Event you bind data to the second ListView.
I can't write much more it would take much time.
Hope it helps.

How to set an empty string as a default value for a DataSource parameter in ASP.NET?

This doesn't work. I've got an exception from SQL databse that column does not allow nulls.
<asp:SqlDataSource ID="MyDataSOurcet" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
InsertCommand="INSERT INTO MyTable(Name) VALUES (#Name) WHERE NameID = 1"
<InsertParameters>
<asp:Parameter Name="Name" Type="String" DefaultValue=""/>
</InsertParameters>
</asp:SqlDataSource>
You could try
<asp:Parameter Name="Name" Type="string" DefaultValue=""
ConvertEmptyStringToNull="false" />
But I thought that was default.
try this:
<asp:SqlDataSource ID="MyDataSOurcet" runat="server" OnInserting="MyDataSOurcetInserting" ... >
//cs
protected void MyDataSOurcetInserting(object sender, SqlDataSourceCommandEventArgs e)
{
//check if nothing has been inserted then
e.Command.Parameters["Name"].value = DBNull.Value;
}
Good luck!

Categories

Resources