I'm using a class named Connection.
Here is my class code:
public static string Username;
Then somewhere in my main windows form I'm searching in a datagridview and I use Connection.Username.
I want to set in my SqlDataReader do search
where Username = Connection.username
but only in case that this is not null.
Here is my main code:
SqlDataAdapter sda = new SqlDataAdapter("select UserName from CustomerTrans where UserName='"+Connection.Username+"'" , con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
}
I want to avoid the case when Connection.Username is null to return all results.
You can just add a simple if statement before your expressions.
if(Connection.Username!=null){
SqlDataAdapter sda = new SqlDataAdapter("select UserName from CustomerTrans where UserName='"+Connection.Username+"'" , con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
}
}
Related
I have to bind the combo box with the following code:
private void getCompanydata()
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.AppSettings["RL_InventoryConnection"]);
if (con.State == ConnectionState.Closed)
con.Open();
MySqlCommand cmd = new MySqlCommand("select comp_id, concat(comp_name,'-', comp_add) as company from companymaster;", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dr.ItemArray = new object[] {0, "--Select Delivery Location--" };
dt.Rows.InsertAt(dr, 0);
comboBox1.DisplayMember = "company";
comboBox1.ValueMember = "comp_id";
comboBox1.DataSource = dt;
}
In another method, I want to access comp_id which is bound with valueMember. I am trying with the following code, but it’s not working:
private void SaveData()
{
string company = comboBox1.Text.ToString();
int companyid = Convert.ToInt32(comboBox1.SelectedValue);
}
You want to try use combobox1.SelectedValue instead of combobox1.MemberValue.
More Details in the documentation here...
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.listcontrol.selectedvalue?view=windowsdesktop-6.0#system-windows-forms-listcontrol-selectedvalue
Similar answer link below...
https://stackoverflow.com/a/6901118/4462984
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);
}
}
I have table which has composite keys in order to retrieve data from two different tables. I have created stored procedures to do that and it works fine:
Stored procedure:
ALTER PROC dbo.spp_adm_user_user_group_sel
AS
BEGIN
SET NOCOUNT ON
SELECT
g.name AS Group_Name, u.fullname, u.designation,
u.email, u.mobile
FROM
TBL_ADM_USER_GROUP g, TBL_ADM_USER u
WHERE
g.id = u.group_id
AND (g.deleted IS NULL OR g.deleted <> 1)
END
The result is like this:
Group_name fullname designation email mobile
Alex fffffffff Engineer sss#mail.come 3333333333
Jon hhhhhhhhh programmer hh#mail.com 020202028347
As you can see, the stored procedure does not have any parameters. How to read this output and return it as list using C#?
Code:
public List<string> GetData()
{
using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
{
string group;
DataTable dt = new DataTable();
List<string> details = new List<string>();
SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
details.Add(group);
}
}
return details;
}
Change your code to this
public List<yourClass> GetData()
{
using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
{
DataTable dt = new DataTable();
List<yourClass> details = new List<yourClass>();
SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
yourClass obj = new yourClass();
obj.fullname= dr["fullname"].ToString();
obj.email= dr["email"].ToString();
details.Add(obj);
}
return details;
}
}
If You Got The Code To Execute Store Procedure,and
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Code Returning Your Desired Result In Dt,Then You Can Just Try Something like That.
foreach (DataRow dr in dt.Rows)
{
details.Add(dr.Field<String>("Your_Coumn_Name_In_Dt"));
}
Or
foreach (DataRow dr in dt.Rows)
{
details.Add(Convert.ToString(dr[0]));// 0 is the Column Index
}
Returning A DetailList,
Way1: create a Model Class that contains your properties and return list of that model Class.
public class Details{
public string Group_name {get;set;}
public string fullname { get; set; }
public string designation { get; set; }
public string email{ get; set; }
public string mobile{ get; set; }
}
And Change Your Method.
public List<Details> GetData()
{
using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
{
DataTable dt = new DataTable();
List<Details> details = new List<string>();
SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Details group=new Details();
group.Group_name =dr.Field<string>("Group_name");
group.fullname =dr.Field<string>("fullname");
group.designation =dr.Field<string>("designation");
group.email=dr.Field<string>("email");
group.mobile=dr.Field<string>("mobile");
details.add(group);
}
}
return details;
}
Way2: If You Don't Want To Create A Model Then a bad solution will be to return a list of objects
public List<Object> GetData() {
using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
var result = from o in dt.AsENumerable()
select (new
{
Group_name =dr.Field<string>("Group_name"),
fullname =dr.Field<string>("fullname"),
designation =dr.Field<string>("designation"),
email=dr.Field<string>("email"),
mobile=dr.Field<string>("mobile")
} as Object);
}
return result.ToList();
}
you can call the stored procedure and take the result into a dataset.
SqlConnection Cn = new SqlConnection("Constr");
SqlCommand Cmd = new SqlCommand("StoredProcName", Cn);
SqlDataAdapter Da = new SqlDataAdapter(Cmd);
DataSet Ds = new DataSet();
Da.Fill(Ds, "TableName"); //Da.Fill(Ds);
Copy the rows of the data table to an array using CopyTo method of Rows collection of Data table and then convert it into list. Of course the List type will be DataRow and not any custom class.
DataTable Dt = Ds.Tables["TableName"]; // DataTable Dt=Ds.Tables[0];
DataRow[] Array = new DataRow[Dt.Rows.Count];
Dt.Rows.CopyTo(Array, 0);
List<DataRow> List=Array.ToList();
if you want to use a custom class then create the class and convert this List of type DataRow to List of type CustomClass as follows.
List<customclass> List1=new List<customclass>();
foreach(var L in List)
{
CustomClass C=new CustomClass();
C.Field1=L[0].ToString();
C.Field2=int.Parse(L[1].ToString());
.....//Assign values to all fields in the custom class
List1.Add(C);
}
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;
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();