I have added textboxes dynamically in a FlowlayoutPanel from SQL table like this
string query = "SELECT* FROM tblA";
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=DummyData;Integrated Security=True"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Label objLbl = new Label();
TextBox objText = new TextBox();
objLbl.Text = reader["A_Name"].ToString();
objText.Name = "txt"+reader["ID"].ToString();
pnlFlow.Controls.Add(objLbl);
pnlFlow.Controls.Add(objText);
}
}
}
It's working fine. Now the problem that I'm facing is when user enters some data in these textboxes. How do I get that data for further processing?
There are a number of ways you could do this, depends on how and when you need to get the values.
If you need to read them all at once, something like:
foreach(Control c in pnlFlow.Controls)
{
if c.Name.StartsWith("txt")
// process the text box
// you might want to use a more distinct naming pattern to be safe
...
}
If you need to process them individually and at different times, you could reference them by name in the Controls collection:
string textBoxName = "txt12345";
string valueText = ((TextBox)pnlFlow.Controls[textBoxName]).Text;
Of course both snippets need better error handling, but I'll leave that to you.
Related
I wants to fetch the data from database using C++.Net. I need to do this irrespective of db used in the system. But i don't want to change my code for each database. I am looking for a solution in C++.Net, please do help..
This is what i have now;
Oracle:
OracleConnection *myOracleConnection;
OracleDataAdapter * myDataAdapter;
DataSet * myDataSet;
myOracleConnection = new OracleConnection(S"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw;");
myOracleConnection->Open();
myDataAdapter = new OracleDataAdapter(S"select dbms_xmlgen.getxml(' select * from SampleTable') from dual ",myOracleConnection);
myDataSet = new DataSet("Sample");
Sql:
`SqlConnection *mySQLConnection;
SqlDataAdapter * myDataAdapter;
DataSet * myDataSet;
mySQLConnection = new SqlConnection(S"Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw;");
mySQLConnection->Open();
myDataAdapter = new SqlDataAdapter(S"select * from [SampleTable]",mySQLConnection);
myDataSet = new DataSet("Sample");`
i wants to do both connection using one connection object. Is there any idea to achieve this???
I can't give you c++ code, but I can help you how to do it. It will be difficult to do it in one connection, but your can get a DataSet back which will work, and you only have to do the code once.
Create a method will return a DataSet, and pass the query as well as what type of connection should be used, in this method depending on tour connection type you do your query and return your result.
You can also add a connectionstring if you wish.
Something like this (it is c# though)
DataSet GetDataSet(string sqlQuery, ConnectionType connType)
{
DataSet dataset = new DataSet("aDataSet");
using (DataTable table = dataset.Tables.Add("aDataTable"))
{
switch (connType)
{
case ConnectionType.MSSQL:
using (var conn = new SqlConnection("Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw"))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
case ConnectionType.Oracle:
using (var conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw"))
{
using (var cmd = new OracleCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
default:
break;
}
}
return dataset;
}
enum ConnectionType { MSSQL, Oracle }
I have list of BuilderString which I want to contain data
public List<int> IDS = new List<int>();
public List<StringBuilder> Items = new List<StringBuilder>();
What's wrong with this code?
SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True");
SqlDataReader rdr2;
SqlCommand cmd2;
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS[i]", con2);
cmd2.CommandType = CommandType.Text;
rdr2 = cmd2.ExecuteReader();
SqlParameter param = new SqlParameter();
param.ParameterName = "#IDS[i]"
while (rdr2.Read())
{
Items[i].Append((StringBuilder)rdr2["item"]);
}
}
You need to rearrange your code a bit:
using (SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True"))
using (SqlCommand cmd2 = new SqlCommand("select item From TransactiontData where idT = #IDS", con2))
{
// add the paramter to the command
cmd2.Parameter.Add("#IDS", SqlDbType.Int);
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
// set the parameter value
cmd2.Parameter["#IDS"].Value = IDS[i];
// only *THEN* call ExecuteReader()
using (SqlDataReader rdr2 = cmd2.ExecuteReader())
{
while (rdr2.Read())
{
// **NOT SURE** what you're trying to do here.....
// First of all, you need to just call Items.Add()
// to add new items to the list - and I'm TOTALLY
// UNCLEAR what you're trying to do casting the reader
// value to a StringBuilder.......
//
// Items[i].Append((StringBuilder)rdr2["item"]);
//
// replaced with what *might* make more sense.....
Items.Add(rdr2["item"].ToString());
}
rdr.Close();
}
}
con2.Close();
}
Points to note:
I would recommend to always put your SqlConnection, SqlCommand and SqlDataReader into using() {...} blocks to ensure proper disposal
you need to add your parameter and set its value BEFORE you call .ExecuteReader()!
Since the query itself never changes - there's no point in creating a new SqlCommand on every iteration. Create the command once - and then just set the parameter value (which is the only thing changing) once per iteration
You need to assign the parameter value in the application code rather than within the query. I'm not sure exactly what you are trying to accomplish by casting the column value as a StringBuilder. Assuming that each StringBuilder item is to contain a single string retrieved from a varchar/nvarchar column, the example below will do that.
for (int i = 0; i < IDS.Count; i++)
{
var cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS", con2);
SqlParameter param = new SqlParameter("#IDS", SqlDbType.Int) { Value = IDS[i] };
var rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
Items.Add(new StringBuilder((string)rdr2["item"]));
}
}
I would like to know if there is any way to fill ObservableCollection directly from SQL server.
Currently I am loading my data into DataTable (using sqlDataAdapter) and do a conversion to ObservableCollection manually and it very inefficient.
How it can be done?
OK, I have found a way to do this:
It can be done using SqlDataReader.
public ObservableCollection<DataItem> LoadCategoriesData()
{
Command = new SqlCommand(StoredProcedure, Connection);
Command.CommandType = CommandType.StoredProcedure;
ObservableCollection<DataItem> myColl = new ObservableCollection<DataItem>();
Connection.Open();
SqlDataReader reader = Command.ExecuteReader();
while (reader.Read())
{
int mainCatID = reader.GetInt32(0);
string categoryName = reader.GetString(1);
//adding row data to observable
myColl.Add(new DataItem(mainCatID, categoryName));
}
Connection.Close();
return myColl;
}
I have a huge form that has around 110 fields columns (single row) that need to be saved in a database.
What is the best approach to insert these many columns into the database using ADO.NET?
I don't think I should be using an insert statement like this, since the query would be very large due to the number of fields.
conn.Open();
string insertString = #"
insert into Categories (CategoryName, Description)
values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
I think of dumping the data into temp file and then adding them into a datatable and then inserting them into database using SqlBulkCopy.
Is there a better approach? How would you handle this situation?
I am afraid there isn't a good shortcut for inserting this number of columns, but using parameters will likely save some debugging time. By using parameters you do not need to worry about things likes apostrophes in strings and type conversions. Here's a sample:
public static void TryThis()
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "YourConnectionString";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Categories (CategoryName, Description) VALUES (#CategoryName, #Description)";
cmd.Parameters.AddWithValue("CategoryName", "Miscellaneous");
cmd.Parameters.AddWithValue("Description", "Whatever doesn't fit elsewhere");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I want select multiple (all) values from table Account.
string query = "SELECT * FROM Account";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
reader.Read();
label1.Text = reader["PasswordHash"].ToString();
connection.Close();
Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.
Thanks in advance.
Because you are not looping through the query results, it shows up only one result.
string query = "SELECT * FROM Account";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
While(reader.Read())
{
label1.Text += " " +reader["PasswordHash"].ToString();
}
connection.Close();
The above code loops through the query results and will give you what you want in a concatenated string assigned to label1.text. You can also view the results by inserting Console.WriteLine(reader["PasswordHash"].ToString()); in the while loop
You should do
while (reader.Read())
// process information
You need to iterate all the information you retrieved.
Sidenote: Use using statements on your SqlConnection, SqlCommand, and SqlDataReader to make sure the objects get disposed correctly.
The reader only advances one record at a time. You'd need to iterate through the result set in a loop:
while (reader.Read()) {
// do something with the current row by accessing reader[]
}
reader.Close();
There are better ways to structure your code but this illustrates the point you were missing and requires the least changes.
You need to loop, something like this:
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
There is an example in the MSDN docs:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
The line reader.Read() will get the next row, so you can use while(reader.Read()) to iterate over the rows.
Looking at your code my recommendation is to use some other object to add the code to. Text of a label is not an appropriate choice.
Try using a foreach loop into a list to retrieve all the data that has been returned.
You need a while-loop;
while(reader.Read()) {
Console.WriteLine("{0}", reader[0]);
}
Using where id = 2 and id = 3 would return zero results as as id=2 and id=3 are mutually exclusive. where id = 2 or id = 3 could work.
while (reader.Read()) { /*Do stuff with current row*/ }
could work for iterating through the results
You need to loop and data reader is best way for your code , for sample ,something like this:
SqlDataReader myReader = myCommand.ExecuteReader();
// Always call Read before accessing data.
while (myReader.Read()) {
Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
}
// always call Close when done reading.
myReader.Close();