Using parameters to configure the table name in an SqlDataSource SelectCommand - asp.net

I have an ASP.NET 3.5 web form with a DropDownList bound to a table of company names in a database. I also have a data bound GridView which I would like to update with data from the database depending on the company name selected in the DropDownList, so that the SelectCommand for the GridView's SqlDataSource is:
SELECT Registration, Telephone, Profile FROM {CompanyName}_VehicleData
Where {CompanyName} is whatever is selected in the DropDownList. I've used the Command and Parameter Editor to create a ControlParameter pointing to the SelectedValue of the DropDownList, but I don't know how to write the SelectCommand query to concatenate the parameter to '_VehicleData'. Any thoughts.

If you are using a sqldatasource you could set the select command in the code behind.
<sqldatasource>.SelectCommand = "select registration, telephone, profile " & _
"from " & <dropdown>.selectedvalue & "_VehicleData"
<sqldatasource>.SelectType = SqlDataSourceCommandType.Text

#Colin: You said that the solution is writing a stored procedure that evaluates whether the concatenated value (DropDown.SelectedValue + "_VehicleData") maps to a real table using the INFORMATION_SCHEMA.TABLES view before injecting it into a SQL command. Can you please give a code snippet for the stored proc?

Related

How to set a default value for reporting services textbox?

I have a textbox in my .rdlc page which gets values from sql server. However, i want to add a default value to the textbox if the value is NULL. Currently, it shows nothing when the value from sql is NULL.
Two ways :-
Do it in the DataSource itself as mentioned by mason in the other answer. If you are using SQL Server, ISNULL() function will help.
You can use the isnothing() function. Ex iif(isnothing(Field!FieldName.Value),"Default Value",Field!FieldName.Value).
Use the ISNULL function.
select username, ISNULL(firstname, "no name") from users

Add record on button click only

I have a form that has the 'data entry' property set to yes. It is bound to a table. When I start filling in the form it automatically saves it. I do not want this to happen. I only want the form to save to the table when I press a button. Any easy way to do this? w/o vba. If i can only do this with vba let me know how to do it that what.
The best way to do this is with an unbound form. When the user clicks save, you can run a query to update your table from the controls.
Using a recordset
Dim rs As Recordset
Set rs=CurrentDB.Openrecordset("MyTable")
rs.AddNew
rs!Field1 = Me.Field1
rs.Update
If you wanted to update a record where you already knew the primary key, you could say:
Dim rs As Recordset
Set rs=CurrentDB.Openrecordset("SELECT * FROM MyTable WHERE ID=" & Me.txtID)
rs.Edit
rs!Field1 = Me.Field1
rs.Update
Using a query that you have created in the query design window
SQL for the query
INSERT INTO MyTable (Field1)
VALUES ( Forms!MyForm!Field1 )
VBA
This will give a warning
DoCmd.OpenQuery "MyQuery"
This will not
CurrentDb.Execute "Query2", dbFailOnError
You could also use dynamic SQL or a query with parameters that you assign in code.

There's a way to include more than one field in combobox control?

I have a combobox (DropDownList) control in my aspx project, linked to a datasource. I would like to show more than one field on the dataTextField (like in MS-Access). It's possible? How can I do it?
You can't specify more than one DataTextField. You need to figure out how to get the fields combined before databinding.
Generally, I accomplish this by modifying the query from the database. For example, if I wanted a full name of an employee in a drop-down list, I'd use the query
Select EmployeeNumber, FirstName + ' ' + LastName AS FullName from EmployeeTable
And set the DataTextField to FullName
If you don't have the flexibility to modify the query (for example, if you don't have rights to the database and are using a stored procedure set up by a DBA), you'd need to instead populate the drop-down in the code-behind. Perhaps have the query fill a DataTable, add a column to the DataTable, and set the newly added Column's value to be the FirstName + ' ' + LastName and set the DataTextField accordingly.
However, the first solution is better in my opinion because it's easier to change teh query (or stored procedure) than to change the code, recompile, and deploy if it needs to change down the road.

Dynamically update ,delete ,insert GridView in ASP.NET

My database tables list in dropdownlist...when i select table from dropdown table display in GridView. I want to edit,delete & insert dynamically in GridView. Please give me solution....
Check out these links:
http://geekswithblogs.net/dotNETvinz/archive/2009/02/22/gridview-insert-edit-update-and-delete--the-ado.net-way.aspx
http://msdn.microsoft.com/en-us/library/aa479339.aspx
Say you have three database tables, Customer, Orders and Products - do you mean the names of these tables appear in your dropdownlist?
If so, when a table name is selected in the dropdownlist (and perhaps an 'Edit' button is clicked), you'll need to bind your GridView to the selected table's data.
You could do this with inline SQL - build it from the DDL:
string _selectString = "SELECT * FROM " + ddlTables.SelectedValue ; //Remember to include the schema in the dropdownlist's value property
And then use this SQL to fetch back the data and bind your grid to it.
A better way would be to wrap up the SQL in a stored procedure that uses SQL Server's INFORMATION_SCHEMA schema (which holds all the database's objects)
CREATE PROCEDURE MySchema.GetTableData
#TableName VARCHAR(Max),
#SchemaName VARCHAR(MAX) --Pass in the relevant Schema
AS
BEGIN
SET NOCOUNT ON
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #TableName
AND TABLE_SCHEMA = #SchemaName
END
and get the data out this way. The only difference to the way you're probably already doing this is to set the SQLCommand's CommandType property to CommandType.StoredProcedure and to pass in the tablename and schema name as SQLParameters.
More information about ASP.Net and Stored Procedures:
http://www.c-sharpcorner.com/UploadFile/gtomar/storedprocedure12052007003126AM/storedprocedure.aspx
Once you've got the data from the table you just use the code & process linked to by #Brian.
hth.

displaying a table's field in a textbox

I have a table and I want to select a field in it and then display it in a text box
something like:
SELECT userName
FROM userTable
WHERE (userLogged = 'ON')
how can I display the selected username in a textbox?
BTW the userLogged indicates wether the user is logged in or not
if the user is logged in then the userLogged will be changed to "ON"
if the user is not logged in it will be "OFF"
I know it's not that practical but I'm still practicing.
I'm using Visual Web Developer 2008 Express
--------- update ----------
I use table adapter procedures for querying
If you're just pulling a single field then the best way is to run your SqlCommand in scalar execution mode; which will return just one field/value.
Imports System.Data.SqlClient
....
Using sqlConn as new SqlConnection("Data Source=YourServer";Trusted_Connection=True;Database=DBName", _
sqlComm as new Sqlcommand("SELECT userName FROM userTable WHERE userLogged = 'ON'", sqlConn)
sqlConn.Open();
dim result as string = sqlComm.ExecuteScalar().ToString
TextBox1.Text = result
End Using
Note: "Trusted_Connection" inside the SQL connection string indicates to use windows authentication to login to the SQL Server; you can replace it with "User Id=Username; Password=Password;"
To set the text property on a textbox you simply call...
TextBox1.Text = "Value";
From your codebehind, If in your aspx page you have a textbox control...
<asp:TextBox ID="TextBox1" runat="server"/>
However there is much missing from your code example and many different ways of accessing a field value from a database
Well, this is a broad question as we don't know how you are querying the database or anything like that. Basically, you just take the result of your query, assuming it is in a DataTable object called dt and do something like this:
myTextBox.Text = dt.Rows[0]["userName"].ToString();
But, I suspect you need more than that. I recommend using the wonderful resources over at:
Learn Visual Studio.NET
It it a great place for beginners and has plenty of tutorials on ADO.NET.

Resources