asp.net insertCommand resulting in NULL values - asp.net

I have two listboxes whose values are sent into a TableC via a button.
<asp:SqlDataSource ID="sql1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>"
SelectCommand="SELECT [Name] + ' (' + [CNbr] + ')' AS FullName, [CNbr] AS CNum FROM [TableA] ORDER BY [Name]">
</asp:SqlDataSource>
<asp:ListBox ID="lst1" runat="server" DataSourceID="sql1" DataTextField="FullName" DataValueField="CNum" AutoPostBack="true">
</asp:ListBox>
<asp:SqlDataSource ID="sql2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>"
InsertCommand="INSERT INTO [TableB] ([CNbr], [RDate]) VALUES (#CNbr, #RDate)"
<InsertParameters>
<asp:Parameter Name="CNbr" Type="String" />
<asp:Parameter Name="RDate" Type="DateTime" />
</InsertParameters>
<asp:ImageButton ID="ibnCheckOutBtn" runat="server"
ImageUrl="./images/vidCheckOutButton.png" onclick="ibnCheckOutBtn_Click" />
ASPX.CS file:
protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
sql2.Insert();
}
I don't really know C# and my class doesn't cover most C#, so I am looking for a solution that doesn't use a lot of behind-code. The error I get is:
Cannot insert the value NULL into column 'CNbr', table 'TableB'; column does not allow nulls. INSERT fails. The statement has been terminated.
However, nulls should not occur because the values are taken from a fully populated listbox. Help?

You will need to assign the values to sql2 insert parameters in a similar way as follows:
protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
sql2.InsertParameters["CNbr"].DefaultValue = this.FindControl("lst1").SelectedValue;
sql2.InsertParameters["RDate"].DefaultValue = DateTime.Now.ToString();
sql2.Insert();
}

Related

how can i access string variable value of .aspx.cs file in .aspx file

i m getting a string value regression as regression = (Session["Regression"]).ToString(); in .aspx.cs file then i want to use this value in .aspx file in SelectCommand of SqlDataSource property as below
SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%#regression%>'"`
.aspx.cs file page_load method is as below
protected void Page_Load(object sender, EventArgs e)
{
if ((Session["UserName"].ToString()) == string.Empty)
{
Server.Transfer("regressionType.aspx");
}
regression = (Session["Regression"]).ToString();
usrname = (Session["UserName"]).ToString();
DataBind();
}
please suggest me how can i do this?
thanks in advance...
You can you Session Variable's value in your SQLDatasource. Like this Example.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [UserTable] WHERE ([userID] = #UserID)">
<SelectParameters>
<asp:SessionParameter Name="UserID" SessionField="UserID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
let us know any other concerns on this..
add Session paramter to your sql Datasource like this
<asp:SqlDataSource SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%#regression%>'"`>
<SelectParameters>
<asp:SessionParameter SessionField="Regression" Name="ParameterName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Try this:
SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%=ReturnRegression()%>'"`
In codebehind:
string regression=null;//Before Page_Load
protected string ReturnRegression()
{
//Write logic here to prevent null being returned
return regression;
}
try this:
public StringBuilder regression = new StringBuilder();
regression.Append((Session["Regression"]).ToString());
Then in the .aspx page (in the selct command), you can use "regression" as:
<% =regression %>

Dynamic query in ASP.Net (WHERE clause in SQLDataSource)

I'm currently trying to loop through an array (two values) and use both values in a query inside the loop. Please see code below. Right now my code doesn't work. I'm trying to populate dynamically the "appType" parameter within the "SelectParameters" tags of the SQLDataSource, but this won't work.
Any suggestion?
<%
Dim appTypes() As String = {"Extranet", "Internet"}
For Each appType As String In appTypes
%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ProviderName = "<%$ ConnectionStrings:CMS.ProviderName %>"
SelectCommand = "SELECT Applications.Name as AppName, Applications.Abbr as AppAbbr, Types.Name as TypeName, Managers.LastName as LastName, Managers.FirstName As FirstName, Managers.EDKeyEmpID as EDKeyID
FROM Types INNER JOIN (Managers INNER JOIN Applications ON Managers.ID=Applications.Manager) ON Types.ID=Applications.Type
WHERE (Types.Name = #appType)
ORDER BY Types.Name, Applications.Name;"
ConnectionString="<%$ ConnectionStrings:CMS %>">
<SelectParameters>
<asp:Parameter DefaultValue="<%=appType%>" Name="appType" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Repeater ID="Repeater1" DataSourceID="SqlDataSource1" runat="server">
<ItemTemplate>
<%#Eval("AppName")%> (<%=appType%>)
</ItemTemplate>
</asp:Repeater>
<% Next %>
Modify your SqlDataSource to have an OnSelecting member:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" OnSelecting="OnSelecting"
Reset your SelectParameters back to normal:
<SelectParameters>
<asp:Parameter Name="appType" Type="String" />
</SelectParameters>
Define this method in your code-behind. Implement the logic as required. Here I've shown a dummy value from your Repeater. It'll be up to you to determine how/where that actually comes from (SelectedItem or something similar).
Protected Sub OnSelecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
e.Command.Parameters("#appType").Value = Repeater1.SomeValue
End Sub

ASP.NET DataSource with parameters for SQL IN clause

<asp:SqlDataSource ID="DataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DbConnection %>"
ProviderName="<%$ ConnectionStrings:DbConnection.ProviderName %>"
SelectCommand="select somefield from sometable where somefield in (?)">
<SelectParameters>
<asp:Parameter DefaultValue="" Name="SomeFiedValue" />
</SelectParameters>
</asp:SqlDataSource>
How (from my codebehind) do I allocate a list of values for the parameter in the above SQL query?
try this.
protected void DataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters["SomeFieldValue"].Value = yourdata;
}
EDIT:
Based on your answers, please have a look at the following website. It explains one way to solve this problem with DB2.
http://www.tek-tips.com/viewthread.cfm?qid=1443561
Based on the comments on that page, a possible solution for your problem could be:
select somefield from sometable where somefield in
(select ? from SYSIBM.SYSDUMMY1)

gridview with multi select listbox

HiI have a list box that is bound to a table in a database. it produces a list of companies. The user will then come along and select multiple companies that they want to view information about, and then they hit a selet button which ill display the company information (e.g company name, company site, address e.t.c) in a gridview underneath. however the issue that i am having is that it only displays ONE of the multiple companies selected and its always the top one.
Can someone please shed some light on how i get all the companies to be displayed in the gridview?
i am programming in vb.net
please see source code below
<asp:ListBox ID="ListBox1" runat="server"
DataSourceID="SqlDataSource11" DataTextField="compName"
DataValueField="compDataID" SelectionMode="Multiple" AutoPostBack="True"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource11" runat="server"
ConnectionString="<%$ ConnectionStrings:IWSRiskAssessmentConnectionString %>"
SelectCommand="SELECT [compDataID], [compName] FROM [tblCompany] WHERE ([compDataID] <> #compDataID) ORDER BY [compName]">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="compDataID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView
ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="compName" HeaderText="compName"
SortExpression="compName" />
<asp:BoundField DataField="Site Name" HeaderText="Site Name"
SortExpression="Site Name" />
<asp:BoundField DataField="Reference Number" HeaderText="Reference Number"
SortExpression="Reference Number" />
<asp:BoundField DataField="Asset" HeaderText="Asset" ReadOnly="True"
SortExpression="Asset" />
<asp:BoundField DataField="Location" HeaderText="Location"
SortExpression="Location" />
<asp:BoundField DataField="Block" HeaderText="Block" SortExpression="Block" />
<asp:BoundField DataField="Room" HeaderText="Room" SortExpression="Room" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:IWSRiskAssessmentConnectionString %>"
SelectCommand="SELECT tblCompany.compName, tblSite.siteName AS [Site Name], tblSite.siteUPRN AS [Reference Number], tblIncMain.incAsset + ' ' + CAST(tblIncMain.incNumber AS varchar) AS Asset, tblIncMain.incLocation AS Location, tblIncMain.incBlock AS Block, tblIncMain.incRoom AS Room FROM tblIncMain INNER JOIN tblSite ON tblIncMain.incSite = tblSite.siteID INNER JOIN tblCompany ON tblSite.siteCompany = tblCompany.compDataID WHERE (tblIncMain.incActive = 1) AND (tblSite.siteActive = 1) AND (tblIncMain.incRemoved = 0) AND (tblCompany.compDataID = #compDataID) ORDER BY [Site Name], tblIncMain.incAsset, tblIncMain.incNumber">
<SelectParameters>
<asp:ControlParameter ControlID="ListBox1" Name="compDataID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
this is the source code :-) please take a look and any help is greatly appreciated
May be DataBind code executes on every request or you are not collecting selected items from the listbox.
Sub page_load()
if Not IsPostBack Then
End If
End sub
and to iterate Listbox items,
For Each item in ListBox1.Items
if item.Selected then
End If
Next
Your data source is only selecting 1 record. The ListBox will return the first value when you use a multiple select ListBox as a ControlParameter.
(tblCompany.compDataID = #compDataID)
What you want to do is have something with an IN statement such as
(tblCompany.compDataID in #compData)
You may need to do something in the code behind.
<asp:ListBox ID="ListBox1" runat="server"
AutoPostBack="True"
DataTextField="compName"
DataSourceID="SqlDataSource11"
DataValueField="compDataID"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
SelectionMode="Multiple">
</asp:ListBox>
Code behind
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = string.Empty;
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected == true)
s += li.Value + ",";
}
if (s != string.Empty)
{
s = s.Substring(0, s.Length - 2); // chop off trailing ,
SqlDataSource2.SelectParameters["compData"].DefaultValue = s;
}
}
NOTE this hasn't been tested but it is one option you can try. Basically you want a IN not a = for your select to get all results.
ok so i added 'in' to my sql statement, however it still only picked up one selection from the list box instead of multiple this is the sql statement:
SELECT tblCompany.compName, tblSite.siteName AS [Site Name], tblSite.siteUPRN AS [Reference Number], tblIncMain.incAsset + " " + CAST(tblIncMain.incNumber AS varchar) AS Asset, tblIncMain.incLocation AS Location, tblIncMain.incBlock AS Block, tblIncMain.incRoom AS Room FROM tblIncMain INNER JOIN tblSite ON tblIncMain.incSite = tblSite.siteID INNER JOIN tblCompany ON tblSite.siteCompany = tblCompany.compDataID WHERE (tblIncMain.incActive = 1) AND (tblSite.siteActive = 1) AND (tblIncMain.incRemoved = 0) AND tblCompany.compDataID in(#compDataID) ORDER BY [Site Name], tblIncMain.incAsset, tblIncMain.incNumber

asp.net dropdownlist

I have two dropdownlists for a search, the 1st list is for the city and the second is for the area within the selected city. I would like to add a default value in the 2nd dropdownlist that will search ALL of the areas by default unless a specific area is selected from the list that contains the areaID for a specific search.
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="cityName" AutoPostBack="true" DataValueField="cityID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Cities]"></asp:SqlDataSource>
<asp:DropDownList ID="DropArea" runat="server" DataSourceID="SqlArea"
DataTextField="areaName" DataValueField="areaID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlArea" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [area] WHERE ([cityID] = #cityID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="0" Name="cityID"
PropertyName="SelectedValue" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Search" onclick="Button1_Click" />
Bind the second from code behind. Create a data table and insert the Select text at the begining and bind the datatable to the DDL.
DataTable dt =
DataRow dr = dt.NewRow()
dr["areaName"] = "All";
dr["SqlArea"] = "All";
tbldata.Rows.InsertAt(dr,0);
DropArea.DataSource = dt;
DropArea.DataBind();
You can try to add for second dropdownlist OnDataBound="DropArea_DataBound" event.
And use in code:
protected void DropArea_DataBound(object sender, EventArgs e)
{
DropArea.Items.Insert(0, new ListItem() {Value = "-1", Text = "ALL"});
}
And then when you handle click event, check:
var value = DropArea.SelectedItem.Value;
if(string.equals(value, '-1')
{
use your logic here
}
Hope it will help with your problem.
Best regards, Dima.
Chris,
I got the idea below from an answer HERE, but basically you want to modify your query to be in the form of the following:
Your Original:
SELECT * FROM [Cities]
Change To:
SELECT City FROM [Cities]
UNION ALL
SELECT 'ALL'
Old question, but you never found an answer.

Resources