gridview with multi select listbox - asp.net

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

Related

How to load Data from a second table in GridView

i have to tables: Users and PrivateMessages.
Users has UserID and Username.
PrivateMessages has the coloumns PMID and Text and SenderID.
(of course it has much more but to explain the problem, its enough)
Now I have a DataSource and a method like this:
public static List<UserPM> GetAllPMsAsSender(Guid userID)
{
using (RPGDataContext dc = new RPGDataContext())
{
return (from a in dc.UserPMs where a.Sender == userID && !a.IsDeletedSender orderby a.Timestamp select a).ToList();
}
}
and bind it to the ObjectDataSource with is bound to the Grid View.
The Grid view now looks like these:
<asp:ObjectDataSource ID="odsOutcome" runat="server"
SelectMethod="GetAllPMsAsSender" TypeName="DAL.PMDAL">
<SelectParameters>
<asp:CookieParameter CookieName="UserID" DbType="Guid" Name="userID" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView ID="gridOut" runat="server" AutoGenerateColumns="False"
DataSourceID="odsOutcome">
<Columns>
<asp:BoundField DataField="PMID" HeaderText="PMID" SortExpression="PMID" />
<asp:BoundField DataField="Text" HeaderText="Text" SortExpression="Text"/>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
</Columns>
</asp:GridView>
So how I can get the Username in this field instead the UserID?
Try using join and select the user name too for your object data source and use the user name to display it instead of user id.
Refer this link How to do a join in linq to sql with method syntax?

asp.net insertCommand resulting in NULL values

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();
}

ASPxGridView and LinqServerModeDataSource, inserting rows by stored procedure

I have a page using ASPxGridView and to fill the GridView I use a LinqServerModeDataSource control who fetches it data through a SQL View from a MS SQL Server. So far so good but here comes the problem.
I want to insert data in the database so I'm building a custom form
<Templates>
<EditForm>
Company Name: <dx:ASPxTextBox ID="CompanyName" runat="server" />
Company Mail: <dx:ASPxTextBox ID="Email" runat="server" />
<dx:ASPxGridViewTemplateReplacement ID="UpdateButton" ReplacementType="EditFormUpdateButton" runat="server" />
<dx:ASPxGridViewTemplateReplacement ID="CancelButton" ReplacementType="EditFormCancelButton" runat="server" />
</EditForm>
</Templates>
Here is an example of the custom form
Pretty basic stuff, in this scenario the Company name goes to one table and the email to another. This is all handled by calling a Stored Procedure. Or thats the plan.
Does anyone know how to do this?
It feels like I've been trying it all, LinqServerModeDataSource1_Inserting, ASPxGridView1_RowInserting and so on but nooo. Here is one of the failing codes. And the devexpress documentation is even worse, but lets not go there its not a happy place.
protected void LinqServerModeDataSource1_Inserting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceEditEventArgs e)
{
// Some magic to insert data here
ASPxGridView1.CancelEdit();
}
So, any advice or help is highly appreciated.
Thanks!
"I want to insert data in the database so I'm building a custom form" ASPxGridView can do all that for you without you having to make a custom template at least with sqldb
If i would define a delete command and or edit command below to the sqldatasource i could already delete and edit the information in the gridview
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
ClientIDMode="AutoID" DataSourceID="SqlDataSource1">
<Columns>
<dx:GridViewCommandColumn VisibleIndex="0">
<EditButton Visible="True">
</EditButton>
<NewButton Visible="True">
</NewButton>
<DeleteButton Visible="True">
</DeleteButton>
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn FieldName="Naam" VisibleIndex="0">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="Adres" VisibleIndex="1">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="Postcode" VisibleIndex="2">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="Plaats" VisibleIndex="3">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Name], [Address], [Postcode], [City] FROM [Somewhere]">
</asp:SqlDataSource>
But you can if you really want to use a custom made insert or delete
protected void ASPxGridView4_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
{
DataColumn[] esl = new DataColumn[] { dt.Columns["SQLWaarde"] };
if (ds.Tables[0].PrimaryKey == null || ds.Tables[0].PrimaryKey == esl)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["SQLWaarde"] };
}
DataRow[] delRow = ds2.Tables[0].Select("IndWaardeType = '" + e.Values[1] + "' AND SQLWaarde = '" + e.Values[2] + "'");
ds2.Tables[0].Rows.Remove(delRow[0] as DataRow);
e.Cancel = true;
ASPxGridView4.CancelEdit();
Session["ds2"] = ds2;
}
protected void ASPxGridView4_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
ndr2 = ds2.Tables[0].NewRow();
ndr2[0] = e.NewValues[0];
ndr2[1] = e.NewValues[1];
ndr2[2] = e.NewValues[2];
ds2.Tables[0].Rows.Add(ndr2);
e.Cancel = true;
ASPxGridView4.CancelEdit();
Session["ds2"] = ds2;
}
That's how i did it last time. I made use of datatables and stored that in sessions bla bla realy just trying out but it works alright.

How do you have multiple controls for a gridview?

For example, I have a gridview and two textboxes.
One textbox is for the text to search for.
The second textbox is an order number to search for.
I want my gridview to populate based on one or the other. I don't know how to tell my form if the user is using a number search by that and if a name, instead search by that.
Thanks for any help.
OK hope you haven't solved this yet because I took a few minutes to come up with an example that I think will do pretty much what you want.
DB access uses a stored procedure but you can use a ObjectDataSource with DAL, or just inline the SQL statement on the SqlDataSource, etc.
Markup:
Product ID:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="You must enter a number"
ValidationGroup="vg1" Type="Integer" Operator="DataTypeCheck"></asp:CompareValidator>
<br />
Description:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
<asp:Button ID="cmdSearch" runat="server" Text="Search" ValidationGroup="vg1" /><br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="spGetProducts"
CancelSelectOnNullParameter="False" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" PropertyName="Text" DbType="String" DefaultValue="" />
<asp:ControlParameter ControlID="TextBox2" PropertyName="Text" DbType="Int32" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
And T-SQL for your query:
CREATE PROCEDURE spGetProducts
#ProductId int = NULL
,#ProductDescription nvarchar(100) = NULL
AS
BEGIN
SELECT [ProductId]
,[ProductDescription]
FROM [Products]
WHERE (
(
(#ProductId IS NULL)
OR
([ProductId] LIKE % + #ProductId + %)
)
AND
(
(#ProductDescription IS NULL)
OR
([ProductDescription] LIKE % + #ProductDescription + %;)
)
);
END
If the user doesn't enter anything in either of the fields, the SqlDataSource will still bind due to SqlDataSource.CancelSelectOnNullParameter = False but the empty parameter will not be sent with the query due to ControlParameter.DefaultValue being set. The stored procedure will then insert the NULL value into the parameter and basically skip that part of the filtering in the WHERE clause.
Hope this helps.
You can check the textboxes by using (TextBox1.Text.Trim.Length > 0) or (TextBox1.Text = "")
It sounds like what you are really asking is how do you filter your data source based on more than one possible filter parameter. Explaining that would require knowing what your data source is. Either way, the gridview is just going to display the filtered results, right?
If you are using SQL for your data source the technique is going to be totally different than filtering a collection in memory. So more information on that would be helpful.

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