programmatically change table names in .net strong typed dataset - asp.net

hi
I've developed an application using strong-typed dataset with .net framework 3.5.
is there a way to change the source table for a tableadapter programmatically?
thnx

There are a couple of ways that you can do this. First you could just add a new query that pulls from the different table, and then execute the method for that query, as long as the columns match it will work.
If you need to dynamically change the one of the statements you can access the command collection of the table adapter, it is protected though, so the easiest way to do this is to create a partial class to extend the one generated by the designer. Once you do this you can add your own method to return the data. You can use adapter.CommandCollection[0].CommandText to get and set the SQL for the the default GetData command that is created.
Once you do this you can change it, clear out the parameters, add new parameters or whatever you want to do, then you set the CommandText with the altered SQL, and call GetData or whatever you named the command and it will execute and return as usual.
Here is a code example:
using System.Data.SqlClient;
namespace DataTableAdapters
{
public partial class Data_ItemTableAdapter
{
public Data.Data_ItemDataTable GetDynamicExample(string SearchValue)
{
using (Data_ItemTableAdapter a = new Data_ItemTableAdapter())
{
SqlCommand cmd = a.CommandCollection[0];
cmd.Parameters.Clear();
string SQL = #"Select Data_Item_ID, Data from Data_Item where
SearchValue = #SearchValue";
cmd.CommandText = SQL;
cmd.Parameters.AddWithValue("#SearchValue", SearchValue);
return a.GetData();
}
}
}
}

Related

Displaying of the data in the gridview based on the search criteria using generics concept of .net

i am new to .net..i have to develop an asp.net application.
The UI of the web page will have a Data-bound Grid control on the Home page and there will be a Textbox where users can enter their search criteria.
I know to do this by using ado.net concept...
But i am supposed to do it using generics concept.How can i store the values in the generic list or dictionary of .net and filter the data based on the text entered in the text box.
Please help me out..
Thanks in advance..
You can indeed bind a GridView to List<T>, I do it all the time, like this:
Create a POCO for the data
public class SomeData
{
public string SomeField {get;set;}
public string SomeOtherField {get;set;}
}
Build the list (either manually or as a result a DB query) e.g.
var mylist = new List<SomeData>();
var myitem = new SomeData()
{
SomeField = "Hello",
SomeOtherField = "World"
};
To Filter the data do something like this:
myfilter = MyTextBox.Value;
mylist = mylist.Where(somedata => somedata.SomeField.Equals(myfiltervalue)).ToList();
Bind it to the GridView
mygridview.DataSource = mylist;
mygridview.DataBind();
And this is it!!
I assume you know ado.net and how to bind gridview.
You just need to iterate through your database resultset and add it to list and bind it.
Following link might help you to begin with:
http://www.aspsnippets.com/Articles/How-to-bind-GridView-with-Generic-List-in-ASPNet-using-C-and-VBNet.aspx
Pass your textbox value to your database query/stored procedure as parameter and return the result based on search value.
Edit:
You may want to use FindAll, Find method.
Check below link:
http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx

Changing dataset connection string in web config at runtime

I have a c# generated dataset.
How can I change the connection string so I can use the dataset with another (identically structured yet differently populated) database?
This has to occur at runtime as I do not know the server or database name at compile time. I am using c# 3.5.
I think there is no simple way and you cannot change the Connection-String programmatically for the entire DataSet since it's defined for every TableAdapter.
You need to create the partial class of the TableAdapter to change the connection-string since the Connection property is internal (if your DAL is in a different assembly). Don't change the designer.cs file since it will be recreated automatically after the next change on the designer. To create it just right-click the DataSet and chose "show code".
For example (assuming the TableAdapter is named ProductTableAdapter):
namespace WindowsFormsApplication1.DataSet1TableAdapters
{
public partial class ProductTableAdapter
{
public string ConnectionString {
get { return Connection.ConnectionString; }
set { Connection.ConnectionString = value; }
}
}
}
Now you can change it easily:
var productTableAdapter = new DataSet1TableAdapters.ProductTableAdapter();
productTableAdapter.ConnectionString = someOtherConnectionString;
Here's a screenshot of my sample DataSet and the created file DataSet1.cs:
ide mvs 2008
in your settings.designer.cs verifier or edit this
public string NamOfappConnectionString{
get {
return ((string)(this["NamOfappConnectionString"]));
}
//add this line
set {
this["NamOfappConnectionString"]=value;
}
}
//atr untime use this
string myconnexion = "Data Source=" + txt_data_source.Text + ";Initial Catalog=" + txt_initial_catalog.Text + ";Persist Security Info=True;";
ConfigurationManager.AppSettings.Set("NamOfappConnectionString", myconnexion);
//save into setting
Properties.Settings.Default.NamOfappConnectionString= myconnexion;
Application.Restart();

Retrieve data tables from database with stored procedure

Let me explain you in details the scenario that I am having and the solution I am looking for.
Firstfully, I created a stored procedure that outputs simple things such as 2 tables and a message 'don't stop here'"
T-SQL:
USE [mydb]
GO
/****** Object: StoredProcedure [dbo].[BackupDatabase] Script Date: 2/26/2013 11:29:10 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[testing]
AS
BEGIN
select 'A' firstname, 'B' lastname;
print 'dont stop here'
select 1 final
END
Up until now I used to retriew the tables in a single manner by using datarowcollection class, and my static method looked like this:
C#:
public static class DataMan
{
public static DataRowCollection SelectData(string sql)
{
SqlDataSource DS = new SqlDataSource(CS, sql);
return ((DataView)DS.Select(DataSourceSelectArguments.Empty)).ToTable().Rows;
}
public static string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
where I can easily get what i needed like here, and locate what evver row I wanted:
DataRowCollection people = Util.SelectData("Select * from students")
But now I am planning to create a stored procedure Like I mentioned above and do somthing like this, for instance:
**DataTableCollection** people = Util.SelectData("exec dbo.Testing")
UPDATE:
so I can locate the specific table from my storedprocedure.
I have tried to use DataTable, DataSet, DataTableCollections but no success.I can't use them in proper way.
Please help me
Thank You
Although it can be used in code-behind as you're illustrating here, the SqlDataSource is more typically used in a declarative manner on an ASP.NET markup page. However, given what you've started, when calling a stored procedure, you should set the SqlCommandType to StoredProcedure, supply the name of the procedure to SelectCommand, and return a DataReader. The DataReader, in turn, supports a NextResult() method that you can call to retrieve each discrete result set your procedure provides. Here is a framework of pseudo code that tries to illustrate how you might leverage this:
// pseudo code
void stub()
{
SqlDataSource d = new SqlDataSource(*connection string*);
d.DataSourceMode = SqlDataSourceMode.DataReader;
d.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
d.SelectCommand = "dbo.Testing";
// set some parameters
d.SelectParameters.Add("Parameter1Name","Parameter1Value"); // must be tailored to your proc!!
d.SelectParameters.Add("Parameter2Name","Parameter2Value"); // must be tailored to SqlDataReader r = (SqlDataReader) d.Select();
while (r.HasRows)
{
while (r.Read())
{
// do something with each row
}
// advance to next result set
r.NextResult();
}
r.Close();
}

DataTableMapping using adapter.FillSchema method applied on a Stored Procedure

this is a method i was reading about #MSDN ,
my question is if for an example i would like to use it on a stored procedure
with the fact that the query of that stored procedure is already specifying columns to select from the table like following :
SELECT Columnsome, columnother, , , , ...FROM thisSQLdbTable
though i would like to implement the approach of that specific method , it seems very advanced from a little research i have made on
"the best way" available to extract data from SQL Server into Asp.net DataTable.
public static DataTable GetCustomerData(string dataSetName,
string connectionString)
{
DataTable table = new DataTable(dataSetName);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT CustomerID, CompanyName, ContactName FROM dbo.Customers", connection);
DataTableMapping mapping = adapter.TableMappings.Add("Table", "Customers");
mapping.ColumnMappings.Add("CompanyName", "Name");
mapping.ColumnMappings.Add("ContactName", "Contact");
connection.Open();
adapter.FillSchema(table, SchemaType.Mapped);
adapter.Fill(table);
return table;
}
}
or is it not the method to use if i am querying via SP that specifies the selected column
i could actually drop that stored procedure if it is not requiered to select /specify columns
the stored procedure is doing a specific calculation and updates the table with results of calculation then i am switching it's "MODE" to select results from the table that was updated.
what i did is recyceling (; giving it a parameter (bit type)
stored procedure then asks for the value of supplied bool / bit Parameter,
if its is status true it updates (doing its original task it was made for)
if its false its doing a select oporation so i am using it as i would with 2 separated commands
but now that i have search for a better way to extract data from db into a Data table
i give up on the two way SP and i will make a selection via the exaple above if they're not intended to be used thogether as with my current SP that does preselection when servs the GetCustomersData() above.
So the question is do i need to let the function to make the selection or can i serve it with my sp ready made selection to implemet it with GetCustomersData() in the way that it will only do rest of task and only mapp the columns that was preselected
Still a bit confused on your actual requirement but here goes:
I See you are using a direct query in your C# code, 'best way' would be to make a SP out of it then say:
SqlCommand command = conn.CreateCommand();
SqlDataAdapter sqlAdapter = new SqlDataAdapter(command);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "sp_GetCustomerData";
Then after you have added parameters if needed do:
conn.Open();
sqlAdapter.Fill(dtResult);
conn.Close();
Where dtResult is Datatable.
So you do not need to do any mapping in this case, and since you are using a SP from the Database it will work faster than your direct query and you can change the query logic any time without the need of re deploying your code.
Stored procedures are perfectly valid in this use case. however, if you want more of a properly mapped table, you have several options, some of which go beyond the use of DataTables.
You can use strongly typed DataSets or perhaps use an ORM (object relational mapper).
ref: Typed Datasets: http://msdn.microsoft.com/en-us/library/esbykkzb(v=vs.71).aspx
ref: What is an ORM : http://en.wikipedia.org/wiki/Object-relational_mapping
EXAMPLES OF ORM'S
ref: Entity Framework : http://msdn.microsoft.com/en-us/data/ef.aspx
ref: NHibernate: http://nhforge.org/

How to design Crystal report with Dynamic Data

Good Afternoon Developers,
This is my function to generate the crystal Report,This will take the Report Name and ReportQuery as a input parameter and will generate a dataset , With this dataset how can i design my Report??Because this is Generated at the runtime , How can i access that to generate my ReportDesign??
public void fnLoadDataToReport(string rptName, string rptQuery)
{
try
{
DataSet myDS=new DataSet();
// crReportDocument.Load(Server.MapPath("Reports\" & RptName), OpenReportMethod.OpenReportByTempCopy);
crReportDocument.Load(Server.MapPath("Reports\\" + rptName ));
SqlConnection myConnection=new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
SqlCommand myCommand=new SqlCommand(rptQuery,myConnection);
SqlDataAdapter MyDA=new SqlDataAdapter(myCommand);
MyDA.Fill(myDS,"ReportTable");
crReportDocument.SetDataSource(myDS);
crvReportGeneration.ReportSource=crReportDocument;
crvReportGeneration.ShowFirstPage();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
Any help is appreciable....!
All you need is an XML schema definition of the Dataset to be able to design the report. this can be achieved by the following code.
private void WriteSchemaToFile(DataSet thisDataSet){
// Set the file path and name. Modify this for your purposes.
string filename="mySchema.xml";
// Write the schema to the file.
thisDataSet.WriteXmlSchema(filename);
}
now add the above created file to your project.
Now while designing the report select Database expert and select the xml file under Project. and add it (just like you add tables or views).
Now you are good to go. The rest of the steps are same.
Just make sure the name of the XSD schema and the table name in your Dataset match exactly.
Why are using DataSet as the source for the report. Instead of that if you use a stored procedure as the source, it will solve your problem and also maintenance will be much more easier

Resources