How to load Data from a second table in GridView - asp.net

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?

Related

ASP.NET GridView & SqlDataSource FilterExpression - Column name with hash / pound symbol

I am working with a brilliantly designed table, where the primary key column contains a #: OTTXN#
I need to be able to select and display these values in the GridView which is populated from my SqlDataSource, which is working fine.
When i add FilterExpression=" = '{0}'" then the code craps out on me, because the column name has a hash tag / pound symbol in it.
I'm able to alter the select statement to use an alias without the pound symbol, but SQL where clauses dont allow you to use a column alias.
Any way i can get this to work?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="dsIseries">
<Columns>
<asp:BoundField DataField="OTTXN#" HeaderText="OTTXN"
SortExpression="OTTXN#" />
<asp:BoundField DataField="OTWODT" HeaderText="OTWODT"
SortExpression="OTWODT" />
<asp:BoundField DataField="OTBAD1" HeaderText="OTBAD1"
SortExpression="OTBAD1" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="dsIseries" runat="server"
ConnectionString="<%$ ConnectionStrings:VM520ConnectionString %>"
ProviderName="<%$ ConnectionStrings:VM520ConnectionString.ProviderName %>"
SelectCommand='SELECT ottxn#, otwodt, otbad1
FROM kivalib.ortxnpf
fetch first 100 rows only'
FilterExpression=" = '{0}'">
<FilterParameters>
<asp:ControlParameter ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
EDIT
Without making changes to the database... is there a way i could query the columns from the code-behind and pass the results back to the SqlDataSource or GridView with the values & altered column name?
I would create a VIEW in the DB that includes all the relevant columns with better names and then query from that view.

SqlDataSource won't retrieve logged in user's data from database?

I tried retrieving the user's data based on the logged in UserId, but no progress. Any suggestions?
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Get a reference to the currently logged on user
MembershipUser currentUser = Membership.GetUser();
// Determine the currently logged on user's UserId value
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Assign the currently logged on user's UserId to the #UserId parameter
e.Command.Parameters["#UserId"].Value = currentUserId;
}
And this is the SqlDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString='<%$ ConnectionStrings:NaviConnectionString %>'
SelectCommand="SELECT [UserId], [FirstName], [LastName] FROM [UserProfiles] WHERE ([UserId] = #UserId)">
<SelectParameters>
<asp:Parameter Name="UserId" Type="String"></asp:Parameter>
</SelectParameters>
</asp:SqlDataSource>
And this is the GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKFFeyNames="UserId" DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display."
DataKeyNames="UserId">
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId" SortExpression="UserId" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
</Columns>
</asp:GridView>
There are no data records to display.
However, when I execute the code in query builder, it works.
So I need to get the UserId manually from the database.
Then go to the query builder then execute then paste the userid in to the value of UserID.
Then it displays the correct data based on the UserId:
I also tried changing it to this:
<SelectParameters>
<asp:Parameter Name="UserId" Type="Empty" DbType="Guid"></asp:Parameter>
</SelectParameters>
You should set a break point and see if currentUserId is populated. I believe that it is. If so, then retrieving the UserId is not the problem, but instead the problem is setting the parameter value or selecting the data.
I think you need to change the type of your parameter from string to Guid
<SelectParameters>
<asp:Parameter Name="UserId" Type="Guid"></asp:Parameter>
</SelectParameters>
Just Change This:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Get a reference to the currently logged on user
MembershipUser currentUser = Membership.GetUser();
// Determine the currently logged on user's UserId value
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Assign the currently logged on user's UserId to the #UserId parameter
e.Command.Parameters["#UserId"].Value = currentUserId.ToString();
}
in parameter types there is no guid option. (Also in above codes sql data source has not been set SqlDataSource1_Selecting.) How could it be answer? Just declare parameter name and its ok.
<asp:Parameter Name="UserId"></asp:Parameter>

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

Data binding boundfields in web form

I have the following DetailsView, with several BoundFields, and SQlDataSource that populates the fields:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="TICKET_ID"
DataSourceID="SqlDataSource1" HeaderText="Completed IT ticket information"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center">
<Fields>
<asp:BoundField DataField="TICKET_ID" SortExpression="TICKET_ID" Visible="False" />
<asp:BoundField DataField="SUBMITTED_BY" SortExpression="SUBMITTED_BY" Visible="False" />
<asp:BoundField DataField="TICKET_TITLE" HeaderText="Ticket Description" SortExpression="TICKET_TITLE" />
<asp:BoundField DataField="SUBMITTED_BY" HeaderText="Submitted By" SortExpression="SUBMITTED_BY" />
<asp:BoundField DataField="SOLUTION_NOTES" HeaderText="Solution Notes" SortExpression="SOLUTION_NOTES" />
<asp:BoundField DataField="EMAIL_HISTORY" HeaderText="Email History" SortExpression="EMAIL_HISTORY" />
<asp:BoundField DataField="COMPLETED_BY" HeaderText="Completed By" SortExpression="COMPLETED_BY" />
<asp:BoundField DataField="COMPLETE_DATE" HeaderText="Completed Date" ReadOnly="True" SortExpression="COMPLETE_DATE" />
</Fields>
</asp:DetailsView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TTPRODConnectionString %>"
SelectCommand="SELECT USR_ITFAC.TS_ID AS TICKET_ID, USR_ITFAC.TS_EC1_SUBMITTER AS SUBMITTED_BY, USR_ITFAC.TS_TITLE AS TICKET_TITLE, USR_ITFAC.TS_SOLUTION_NOTES AS SOLUTION_NOTES, USR_ITFAC.TS_EMAIL_HISTORY AS EMAIL_HISTORY, TS_USERS.TS_NAME AS COMPLETED_BY, DATEADD(HOUR,-8,USR_ITFAC.TS_CLOSEDATE) AS COMPLETE_DATE FROM USR_ITFAC INNER JOIN TS_USERS ON USR_ITFAC.TS_COMPLETED_BY = TS_USERS.TS_ID WHERE (USR_ITFAC.TS_ISSUEID = '00033')">
<SelectParameters>
<asp:QueryStringParameter Name="ts_id" QueryStringField="id" />
</SelectParameters>
</asp:SqlDataSource>
I hard-coded a value at the end of the query '00033', which is the ID of a record I know is in the database. I tested the query and it returns a value as expected, what I'm trying to do is fetch the values of the BoundField in the code-behind after a user has pressed a button.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
''Use a Dictionary to store answers to questions that were marked poor or fair
Dim answers As New Dictionary(Of String, String)
''For Each test
For Each dv_row As DetailsViewRow In DetailsView1.Rows
''Print rows data to console
Next
Catch ex As Exception
lblWarn.Text = "<br /><b>Please answer all the questions on this survey</b><br />"
'Response.Write(ex)
End Try
End Sub
Above I'm doing a test to fetch the values and print them onscreen, the problem is that the row count is 0, I'm not sure why that is. I expected the row count to be 8, when debugging I notice that the field count is 8, but I'm not sure how to get the values from the fields. I thought the way to get row data was something like:
Dim rowText As String = DetailsView1.Rows(0).Cells(1).Text
But when I try that I get a Null exception. Any insight is appreciated.
I misread the code. FindControl() is effective when using templates.
Try instead to use the FindControl(controlID) method on your details view to find your data-bound control. The method returns an object of type Control, so you'll probably have to type cast the result to get any real use out of it.
Was able to get it up and running. Turns out the BoundFields were not getting populated because the parameter in the QueryStringField, namely "id", was not being specified in the request URL. To resolve this I first tried to rewrite the URL path on Page_Load, that didn't work, so I just created a separate page with a hyperlink to the page I'm working on with a variable appended to the end of the URL which provides the QueryString for the SQLDataSource to reference. More on the QueryString property here.

asp.net sqldatasource detailview: how to set proper select statement

My page load event looks like this....
SqlDataSource1.ConnectionString = Connection.ConnectionStr;
SqlDataSource1.SelectCommand = "select firstname,lastname from customer";
SqlDataSource1.InsertCommand = "CustRec_iu";
SqlDataSource1.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource1.InsertParameters.Clear();
SqlDataSource1.InsertParameters.Add(new Parameter("firstname", DbType.String));
SqlDataSource1.InsertParameters.Add(new Parameter("LastName", DbType.String));
SqlDataSource1.InsertParameters.Add(new Parameter("Active",DbType.Int16,"1"));
The detailview control setting looks like this....
<asp:DetailsView ID="dvCustDetails1" runat="server" AutoGenerateRows="False"
DataSourceID="SqlDataSource1" Height="149px" Width="469px"
OnItemInserted=dvCustDetails1_ItemInserted
>
<Fields>
<asp:BoundField DataField="FirstName" HeaderText="First Name"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name"
SortExpression="LastName" />
<asp:CommandField ButtonType="Button" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
Right after insert functionality is done, I would like to capture the custid from customer table which is identity column, some how extract it and select table with that record like
select * from customer where custid = #custid.
Then after the control renders after insert, I would like it to show the newly inserted record based on the above select statement.
Also, I would like detailsview to show update button so I could update the record.
How would i accomplish that??
I find very little documentation out there in google search or even print books.
You want to use the sqldatasource's OnSelected event with a return parameter from the SQL call.
Add this to the sqldatasource
OnSelected ="sqlds_Selected"
and implement it something like:
protected void sqlds_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
//get the command object from the arg and
//then you can get to the parameter value
e.Command.Parameters["#CustomerID"].Value
//then set this to your detailsview key
}

Resources