add non specific number of dataset rows into a list - c#

I am trying to insert a non specific number of rows from a dataset into a list by using a foreach. But I am unsure how to add a non specific number of items to a list from a dataset.
public void DeviceReset(string r)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"SELECT installation_id FROM masterinstallationmaps WHERE masterinstallation_id = '" + r + "' ";
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
I am picking out the installation_id from my masterinstallationmap table and if it contains more than 0 rows it should run the foreach to put the rows into the list, otherwise it should run a foreach only inputting 1 item to the list.
List<int> instIdList = new List<int>();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
//How to insert all rows from the dataset?
}
}
else
{
instIdList.Add(1);
}
The else statement works fine, but nothing happens if the Dataset have more than 0 rows.
I am unsure what to put into the foreach:
foreach (DataRow row in ds.Tables[0].Rows)
{
//How to insert all rows from the dataset?
}

Why can't you just add the value like
foreach (DataRow row in ds.Tables[0].Rows)
{
instIdList.Add(Convert.ToInt32(row["installation_id"]));
}

Related

How to get first item from comboxbox in c#?

I fill one combobox with two columns from database with this code:
foreach (DataRow dr2 in dt2.Rows)
{
comboBox1.Items.Add(dr2["Station"].ToString() + " - " + dr2["Ime"].ToString());
}
dbconn.Close();
and combobox look like this:
Now I want to take only first item from this combobox (the numbers) and put into my query for data from database.
I want variable Stations to be with first item from combobox.
I try to get the first index from combobox, but when I debug I see value on the variable is -1 everytime..
The code:
var Stations = comboBox1.SelectedIndex = -1;
MySqlCommand cmd = new MySqlCommand("CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('"+ dtnow +"', " + Stations + ", 5)", dbconn);
MySqlDataAdapter da = new MySqlDataAdapter();
dbconn.Open();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
dataGridView1.DataSource = dt;
}
dbconn.Close();
I upload a picture from debug mode:
I want variable Stations to be with first item from combobox
Instead of
var stations = comboBox1.SelectedIndex = -1;
use
comboBox1.SelectedIndex = -1;
var stations = comboBox1.SelectedText; // or Text

Getting "This row already belongs to another table & Input array is longer than the number of columns in this table."

if I used finalTable.Rows.Add(row.ItemArray) it gives me this error "Input array is longer than the number of columns in this table."
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT CustomerName FROM Customers";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable finalTable = new DataTable();
//finalTable.TableName = "Customers";
if (ds.Tables.Count > 0)
{
int i = 1;
DataTable firstTable = ds.Tables[0];
//firstTable.TableName = "Customers";
foreach (DataRow row in firstTable.Rows)
{
if (i == 5)
{
firstTable.NewRow();
i = 0;
}
finalTable.Rows.Add(row.ItemArray);
i++;
}
}
Repeater1.DataSource = finalTable;
Repeater1.DataBind();
con.Close();
and if i used this finalTable.Rows.Add(row), it gives me "This row already belongs to another table".
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT CustomerName FROM Customers";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable finalTable = new DataTable();
//finalTable.TableName = "Customers";
if (ds.Tables.Count > 0)
{
int i = 1;
DataTable firstTable = ds.Tables[0];
//firstTable.TableName = "Customers";
foreach (DataRow row in firstTable.Rows)
{
if (i == 5)
{
firstTable.NewRow();
i = 0;
}
finalTable.Rows.Add(row);
i++;
}
}
Repeater1.DataSource = finalTable;
Repeater1.DataBind();
con.Close();
}
don't know how to solve it, any solution please?
below is a method that allow you select data from your database by TSQL (select * from table1 ...) then return as datatable and continue processing (eg , bind table)
This is how
1) built a connection string , If you are developing web apps , go to web.config file add below , change parameter according your SQL environment setup.
<configuration>
<connectionStrings>
<add name="PSDatabaseConnectionString" connectionString="Data Source=YourSQLserverName\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
....
2) then build a method to accept SQL statement and return multiple rows data as datatable . In below code , you do not need to define your datatable column structure , SQL will dynamic built it based on your SQL select statement
public static DataTable RunSQL_DML_FillDataGrid(string TSQL)
{
string connectionString = ConfigurationManager.ConnectionStrings["PSDatabaseConnectionString"].ConnectionString;
SqlDataAdapter dataAdapter;
SqlConnection conn = new SqlConnection(connectionString);
try
{
// Run TSQL on SQL server
dataAdapter = new SqlDataAdapter(TSQL, connectionString);
// MS Term ' Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and return the table.
// MS Term ' Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
return table;
}
catch
{
return null;
}
}
3) Finally , you can bind your data table to other object ( datagridview , datatable ....) . I do not know what object type is Repeater1 inside your code but if it can accept datatable , then it shall bind correctly using the returned datatable

How to get all data in gridcontrol by one click

How to use loop to read all records by one click on the button. I have to print many reports.For each row in the table I need to create a report. And read until the last row of the table . My idea is using loop or index table but i don't know how to do it. This is my code:
private void btnin_Click(object sender, RoutedEventArgs e)
{
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdata1 WHERE Customers = '" + cbbcustomer.Text + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cnn.Close();
XtraReport1 report = new XtraReport1();
report.DataSource = dt;
report.ShowPreviewDialog();
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message);
}
}
You could iterate through the Datatable
foreach(DataRow row in dt.Rows)
{
DataTable dtrow = new DataTable();
dtrow = dt.Clone();
dtrow.ImportRow(row);
XtraReport1 report = new XtraReport1();
report.DataSource = dtrow;
//report.ShowPreviewDialog(); Not sure what happens here but maybe a print method is better suited?
}
Basically for each row you create a datatable with the same structure and import one row. Then its assigned as your datasource. This will iterate through all rows.
For some reasons, I had to change something in my code. I used Mark Vance's code but it didn't work:
DataTable a = new DataTable();
a = ((DataView)ctrlgridviewdulieu0.ItemsSource).ToTable();
foreach (DataRow row in a.Rows)
{
DataTable dtrow = new DataTable();
dtrow = a.Clone();
dtrow.ImportRow(row);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdulieu2 WHERE Khachdat = N'" + dtrow.ToString() + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
da.Fill(dt1);
XtraReport1 report = new XtraReport1();
report.DataSource = dt1;
// report.Print();
cnn.Close();
report.ShowPreviewDialog();
}
catch (Exception ex)
{
cnn.Close();
MessageBox.Show(ex.Message);
}
}

How to remove the duplicate tab page?

How to remove the duplicate tab page name in C# Windows Form? I tried many times, it still show the duplicate items on the tab page.
Example:
My code:
SqlCommand cmd = new SqlCommand("SELECT type FROM Products ORDER BY type ASC", con);
con.Open();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
tabControl1.TabPages.Add(dr["type"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
con.Close();
var cmd = new SqlCommand("SELECT DISTINCT type FROM Products ORDER BY type ASC", con);
con.Open();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
tabControl1.TabPages.Add(dr["type"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
con.Close();
You can filter out duplicated rows with this function
public DataTable RemoveDuplicateRows(DataTable dataTable, string columnName)
{
Hashtable hashTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
//Add a list of all the unique item values to the hashtable, which in turn stores a combination of key, value pair.
//And add duplicate item value in arraylist.
foreach (var dataRow in dataTable.Rows)
{
if (hashTable .Contains(dataRow[columnName]))
duplicateList.Add(dataRow);
else
hTable.Add(dataRow[columnName], string.Empty);
}
//Removing a list of duplicate items from datatable.
foreach (var dRow in duplicateList)
dataTable.Rows.Remove(dRow);
//Datatable which contains unique records will be return as output.
return dataTable;
}

How to convert collections to DataTable for Ado.Net SqlDataAdapter.Update?

How to finish the following function which accept three collection parameters for deleted, inserted and updated records and convert the collections to a DataTable for DataAdapter to update the table?
I found a way to convert List to DataTable at How to fill a datatable with List<T>. However, it doesn't set the insert, update and delete flags in DataTable?
void Save(
IEnumerable<int> deleted,
IEnumerable<Poco1> inserted,
IEnumerable<Poco1> updated)
{
var dt = new DataTable();
.... // Initialize dt with deleted, inserted and update?
using (var con = new SqlConnection(ConnectionStr))
{
con.Open();
var da = new SqlDataAdapter("select * from table", con);
da.Update(dt);
}
}
Or is there a better way to update the database table from these three collections? (C# 3.5)
First off, your going to want to also define the Insert, Update and Delete commands:
// Create the other commands.
da.InsertCommand = new SqlCommand("...how to insert");
da.UpdateCommand = new SqlCommand("...how to update");
da.DeleteCommand = new SqlCommand("...how to delete");
Alternatively you can try to use DbCommandBuilder to do it for you at runtime:
// Create the DbCommandBuilder.
DbCommandBuilder builder = factory.CreateCommandBuilder();
builder.DataAdapter = da;
// Get the insert, update and delete commands.
da.InsertCommand = builder.GetInsertCommand();
da.UpdateCommand = builder.GetUpdateCommand();
da.DeleteCommand = builder.GetDeleteCommand();
Next you need to define the DataTables to match the table you are targeting:
DataTable dt = new DataTable();
dt.Columns.Add(add your columns...)
Then you need to add rows to the DataTable, making sure to mark the row as inserted, updated or deleted.
DataRow dr = dt.NewRow();
dr["your column"] = ...
// Don't forget to add the row to the table!
dt.Rows.Add(dr);
// Once the row is added then go ahead and mark it as deleted, modified or new
dr.Delete()
// or
dr.SetAdded();
// or
dr.SetModified();
It wont work the way you are doing , do like this
using (var con = new SqlConnection(ConnectionStr))
{
con.Open();
var da = new SqlDataAdapter("select * from table", con);
var ds=new DataSet();
da.Fill(ds);
var dt= ds.Tables[0];
// all deleted rows
foreach(DataRow dr in dt.Rows.ToList())
{
if(deleted.ToList().Contains((int)dr["id"]))
{
dr.Delete();
}
//all updated rows
foreach(var poco in updated.ToList()
{
DataRow dr = table.Select("id="+poco.id).FirstOrDefault();
dr["field1]=poco.feild1
....set all updated values
}
//all inserted rows
foreach(var poco in inserted.ToList())
{
var dr= dt.NewRow();
dr["id"]=poco.id;
..set all fields
dt.Rows.Add(dr);
}
}
dt.Accept
da.Update(dt);
}

Categories