I want to read the rows inside a user object, but when I try to fill it to a DataTable, Dts.Variables is not a recognized namespace.
public override void PreExecute()
{
base.PreExecute();
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.Fill(dt, Dts.Variables["User::CRMDataSet"].Value);
foreach (DataRow row in dt.Rows)
{
//insert what you want to do here
}
}
The available namespaces are not related as well.
May I know how can I resolve this?
check on your variables that you have created and the scope is the right one: either package or the script task name.
Also what is your data type: if you have table data then it should be object.
Example:
Related
I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.
I created a class std
public void get()
{
SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
string sql = "select * from std";
con.Open();
SqlCommand cm = new SqlCommand(sql, con);
SqlDataReader dr = cm.ExecuteReader();
while ( dr.Read())
{
string stname = dr["st_name"].ToString();
string nicnum = dr["nic"].ToString();
}
con.Close();
}
Form: I am getting data like this way
std ss = new std();
ss.get();
dataGridView1.Rows.Clear();
If I wrote like this way how to pass data into the datagridview columns? I am stuck in this area
It's easier like this:
public void FillGrid()
{
var dt = new DataTable();
var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with
you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.
I am developing a windows form application in c#. My database is handled in a wcf application. In my wcf application I have a class called lecturer which has a method called view lecturers() as follows. My purpose is to view the lecturers table in a grid view.
public DataTable viewLec()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["resourceAlloc"].ToString());
DataTable dt = new DataTable();
string vw = "select * from lecturers";
SqlCommand cmd = new SqlCommand(vw,con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
return dt;
}
In my IService1.cs:
[OperationContract]
DataTable viewLecturer();
Service1.svc.cs:
public DataTable viewLecturer()
{
Lecturer lec = new Lecturer();
return lec.viewLec();
}
in my windows form application button click event,
private void button2_Click(object sender, EventArgs e)
{
Service1Client obj = new Service1Client();
dataGridView1.DataSource = obj.viewLecturer();
}
When I click the view button the above error occurs, I cannot understand why?
I don't know the exact error of your code, but first thing I want to mention is that using DataTable object as your Data Contract is not the best idea as it contains certain amount of extra data which usually is not consumed by the end applications. But anyway, in your particular case WCF will not be able to serialize your your object as it will not have table name which is mandatory for this class to perform serialization. Try to follow this way:
DataTable dt = new DataTable();
// Must set name for serialization to succeed.
dt.TableName = "lecturers";
I don't see the actual error you have (you should post it to make your answer more clear), but at least this will help you to avoid serialization error.
How would I go about initialising a table adapter properly pragmatically? Normally, I would use the table adapter that get's created for me when I drag and drop the Data Table onto my form, but have never used one in a custom class before.
Cheers!
EDIT:
I think I need to explain my scenario in more detail.
I've added a method on my datatable inside my dataset. I want to be able to call this method from inside a custom class. Therefore I'd need a valid Table Adapter to be created to allow me to do this.
Just like this:
var dt = new DataTable();
using (SqlConnection c = new SqlConnection(cString))
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT ...", c))
{
sda.SelectCommand.Parameters.AddWithValue("#field1", field1);
etc...
sda.Fill(dt);
}
void FillData()
{
// 1
// Open connection
using (SqlConnection c = new SqlConnection(
Properties.Settings.Default.DataConnectionString))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(
"SELECT * FROM EmployeeIDs", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
// dataGridView1.DataSource = t; // <-- From your designer
}
}
}
EDIT:
Why don't you make this method in a separate class that will be called in your data table and wherever else you will need to? You will just make an instance of the class and call the public method of that class.
This is a windows forms application. I have a class Program.cs and a form DeployerConsole.cs with a ListBox on it. I am attempting to loop through the results from the SQL query. I am having trouble and getting a 'Object reference not set to an instance of an object.' error when I try to access the data and insert it into my listbox on the form.
EDIT: The SQL Query is completing successfully and the Console.WriteLine is outputting to the output window properly with the correct data.
static void LoadServers()
{
DeployerConsole DC = (DeployerConsole)Application.OpenForms["DeployerConsole"];
//DeployerConsole DC = new DeployerConsole();
SqlConnection myConnection = new SqlConnection("server=XXX; database=XXX; uid=XXX; pwd=XXX;Integrated Security=true;Connection Lifetime=5;Trusted_Connection=yes;");
myConnection.Open();
DataSet ds = new DataSet();
SqlCommand myCommand = new SqlCommand("SELECT ServerName FROM DeployServers", myConnection);
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
DC.listBox1.Items.Add(dr["ServerName"].ToString());
Console.WriteLine(dr["ServerName"].ToString());
}
}
EDIT: Added Screenshot
Anyone have any suggestions or provide guidance as to what I am doing wrong?
EDIT (ANSWER): Well, I moved the code from the class to the form. No problems accessing the listBox now. However, I still would like to know the solution to this.
It might be worth a try (just for testing purposes) to try:
if(DC.listBox1 != null)
{
DC.listBox1.Items.Add(dr["ServerName"].ToString());
}
That could give you a clue, if which you might need to make sure someplace listBox1 is instantiated.
DC.listBox1 = new ListBox();
EDIT
It might be that DC is not being correctly passed by reference to the static method.
It might be better to change the signature of the Method to accept the form.
static void LoadServers(Form form)
{
...
form.listBox1.Items.Add(...)
... etc.
}
and call it assuming from the form:
Helper.LoadServers(this);
Your problem is probably caused by this line of code:
DeployerConsole DC = (DeployerConsole)Application.OpenForms["DeployerConsole"];
I suspect the OpenForms property is returning null because you have not explicitly set the name of your form (e.g. form.Name = "DeployerConsole";).
I wanted to update my dataset changes to my database, so I used this sort of code:
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(sqladap);
sqladap.Update(ds, TableName);
While it works properly I have used this code for another dataset in my project but the second one does not work. I traced this code and saw the rows of the dataset. It contains both last fetched rows and new rows but the SQLDataAdapter updates any data and also it does not throw an error.
here is the full code:
public static SqlDataAdapter AdapterStoredProcedure(string sp_Name, object obj)
{
ClsEventLogs EventLogs = new ClsEventLogs();
try
{
SqlConnection connection = SQLDBConnection();
SqlDataAdapter sqladap = new SqlDataAdapter(sp_Name, connection);
sqladap.SelectCommand.CommandType = CommandType.StoredProcedure;
if (obj != null)
{
Type t = obj.GetType();
string str = string.Empty;
System.Reflection.FieldInfo[] fields = t.GetFields();
foreach (System.Reflection.FieldInfo field in fields)
{
sqladap.SelectCommand.Parameters.Add(new SqlParameter(field.Name, SqlDbType.VarChar, 200));
sqladap.SelectCommand.Parameters[field.Name].Value = field.GetValue(obj).ToString();
}
}
return sqladap;
}
catch(Exception er)
{
EventLogs.Eventlog("clsDataStore : ExecuteStoredProcedure", er.Message, ClsEventLogs.EventType.etCriticalError, false);
return null;
}
}
// Creating Adapter
SqlDataAdapter dAdap = null;
DataSet ds = new DataSet();
dAdap = clsDataStore.AdapterStoredProcedure("sp_SelectTbl_Client", null);
dAdap.Fill(ds, "tbl_client");
//here is where i'm Updating the dataset
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(sqladap);
sqladap.Update(ds, TableName);
You'll have to look (Debugger) at the generated SQL Update/Insert statements. Most likely they are flawed or even empty.
The CommandBuilder is extremely limited, it only deals with very simple SELECT a, b FROM table statements.
You will probably find that the SP that doesn't work contains a JOIN, computed column or something like that.
Best course: provide your own Update statements or SPs
To ask the dumb question: did you tell your adapter to commit the changes after calling the Update method?
EDIT: OK, now that you've posted your code, I have to ask another dumb question: what are you looking at to determine if the update worked? Are you connecting to a remote database right now, or a test database in the project? If it's the latter, then if you are rebuilding each time (something I'm in the habit of doing) then your working copy of the database (in the \bin directory) gets blown away and replaced with a fresh copy from wherever it's referenced from in the project. That assumes, of course, that you're using an embedded DB (like MSSQLCE).