How to remove the duplicate tab page? - c#

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

Related

add non specific number of dataset rows into a list

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

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

Where condition is not null

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

How to read stored procedure output and return it as list

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

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

Categories