How to get all data in gridcontrol by one click - c#

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);
}
}

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

How to show all the rows in datagridview?

DataTable dt = db.getProductIdFromCategoriesId(categories_id);
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
show_products.ItemsSource = dt5.DefaultView;
}
this code show one by one rows in datagridview
but i want to show all the product rows having categories_id in datagridview in one go
this is the function FillDataGridfromTree in databasecore class and its object is db
public DataTable FillDataGridfromTree(int product_Id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products.product_id as ID, products.remote_products_id as Remote_ID, products_description.products_name as name,products.products_model as model,products.manufacturers_id as manufacturersId,products.products_image as Image,products.products_price as Price,products.products_weight as Weight,products.products_date_added as dateAdded,products.products_last_modified as lastModified,products.products_date_available as dateAvailable,products.products_status as status,products.products_tax_class_id as taxClass FROM products INNER JOIN products_description ON products.product_id=products_description.products_id where products_description.language_id=1 and products_description.products_id=" + product_Id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable("products");
adapter.Fill(dt);
//show_products.ItemsSource = dt.DefaultView;
return dt;
}
}
this is the function through which i get product_id
public DataTable getProductIdFromCategoriesId(int categories_id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products_id FROM products_to_categories where categories_id=" + categories_id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
DataTable dt = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
how to show all the rows instead of one row in datagridview
CHANGED Try changing your foreach loop to:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
DataTable dt5 = new Datatable();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));
}
show_products.ItemsSource = dt5.DefaultView;
You code is always going to display the last row for a category_id, this is because you're assigning an ItemsSource inside a loop. I've changed the top part to do what you looking for:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
List<DataRow> ProductList = new List<DataRow>();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
if(dt5.Rows.Count > 0)
{
ProductList.AddRange(dt5.Select().ToList());
}
}
show_products.ItemsSource = ProductList.CopyToDataTable().DefaultView;

Stored procedure in C# datagridview instead of listbox

I have a problem with stored procedures.
This code works (with a ListBox)
private void button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sqlCmd = "Drie duurste producten";
SqlCommand cmd = new SqlCommand(sqlCmd, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlCmd;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader.GetValue(0).ToString());
}
}
connection.Close();
}
But how can I add this data to a DataGridView instead of a ListBox?
Thank you!
Change to
......
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable dt = new DataTable();
adapter.SelectCommand = cmd; {
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
......
usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed
SqlDataAdapter is the simplest way to do it.
But it is also possible to create DataTable and populate it manually and assign DataSource value of DataGridView to DataTable instance:
...
DataTable dt = new DataTable("test");
dt.Columns.Add("test");
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = reader.GetValue(0).ToString();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
....
static public long Insert(BillAO ao)
{
try
{
SqlParameter[] Params =
{
new SqlParameter("#Status",ao.Status)
, new SqlParameter("#BAID",ao.BAID)
, new SqlParameter("#PhieuKhamID",ao.PhieuKhamID)
, new SqlParameter("#ThuNganID",ao.ThuNganID)
, new SqlParameter("#Ngay",ao.Ngay)
, new SqlParameter("#SoTien",ao.SoTien)
, new SqlParameter("#LyDo",ao.LyDo)
, new SqlParameter("#GhiChu",ao.GhiChu)
, new SqlParameter("#CreatedBy",ao.CreatedBy)
, new SqlParameter("#CreatedTime",ao.CreatedTime)
, new SqlParameter("#LastModifiedBy",ao.LastModifiedBy)
, new SqlParameter("#LastModifiedTime",ao.LastModifiedTime)
};
int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
return result;
}
catch (Exception ex)
{
if (ex.Message.Contains("duplicate"))
{
return -2;
}
return -1;
}
}
You need to use SqlDataAdapter to get the result of stored procedure in data table.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
you don't need a CommandReader for this, all you have to do is to use DataAdapter and DataSet. and bind the dataset into your DataGridView
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
You can do it with DataTable Or DataSet To Fill Data.... Here i did with DataTable....
Datatable data = new Datatable();
using (SqlDataAdapter adp = new SqlDataAdapter())
{
adp.SelectCommand = cmd;
adp.Fill(data);
GridView1.DataSorce = data;
GridView1.DataBind(); <--- Needed to bind GridView at a time While Filling DataTable data
}
You Can Also Check If DataTable Contains Data Or Not By This Way Before assigning DataTable to Gridview1.......
if(data.Rows.Counnt > 0)
{
GridView1.DataSorce = data;
GridView1.DataBind();
}
public void whateverToolStripMenuItem_Click(object sender, EventArgs e) {
// A previously declared and instantiated OpenFileDialog, i put it from Design Mode, but you can just
// declare it as
OpenFileDialog dlgImport = new OpenFileDialog();
//We show the dialog:
dlgImport.ShowDialog();
// We declare a variable to store the file path and name:
string fileName = dlgImport.FileName;
try {
// We invoke our method, wich is created in the following section, and pass it two parameters
// The file name and .... a DataGridView name that we put is the Form, so we can also see what
// We imported. Cool, isn't it?
importExcel(fileName, gridMain);
}
// It is best to always try to handle errors, you will se later why it is OleDbException and not
catch (OleDbException ex) {
MessageBox.Show("Error ocurred: " + ex.Message);
}
}

Unable to populate lsitbox in asp.net web application

I am trying to populate a list box from a customers table in SQL database.I tested with WPF list box the code is working good but when i try to implement in asp.net web application i am unable to populate the list box. Here is my code
try
{
string query = "SELECT customer_ID FROM Customers WHERE ID = 1";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(query , conn);
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
listbox1.SelectedValue = row["customer_ID"].ToString();
samplelist.Add(listbox1.SelectedValue);
}
listbox1.DataSource = samplelist;
}
catch (Exception)
{
}
Can any one guide me in the right direction ?
Try using the below code:
try
{
string query = "SELECT customer_ID FROM Customers WHERE ID = 1";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(ds);
listbox1.DataSource = ds.Tables[0];
listbox1.DataTextField = "WORKSTATION_ID";
listbox1.DataValueField = "WORKSTATION_ID";
listbox1.DataBind();
}
catch (Exception)
{
}
foreach (DataRow row in ds.Tables[0].Rows)
{
samplelist.Add(row["WORKSTATION_ID"].ToString());
}
listbox1.DataSource = samplelist;
listbox1.DataBind();
You should be able to trim this down somewhat to the following. You're missing the DataBind() as well.:
try
{
//Existing to fill ds, check table exists, etc.
listbox1.DataSource = ds.Tables[0];
listbox1.DataValueField = "COLUMNNAME";
listbox1.DataTextField = "COLUMNNAME";
listbox1.DataBind();
}
catch (Exception)
{
}

Adding row by row in GridView in runtime

I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}
//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();
add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();

Categories