C# | MVC | DotnetCore | Web API | Blazor | HTML | BootStrap | JavaScript | JQuery | EF | Angular | SQL | Azure
Thursday, 29 May 2014
Wednesday, 28 May 2014
Wrting query for join between two data tables for Multiple Fields
//---------------Wrting query for join between two data tables for Multiple Fields---------------//
var leftOuter = from datavalue1 in dtA.AsEnumerable()
join datavalue2 in dtB.AsEnumerable()
on new { Date = datavalue1["Date"], Time = datavalue1["Time"] }
equals new { Date = datavalue2["Date"], Time = datavalue2["Time"] }
into resultset
from cp in resultset.DefaultIfEmpty()
select new
{
Date = datavalue1.Field<String>("Date"),
Time = datavalue1.Field<String>("Time"),
Series1 = datavalue1 == null ? (decimal?)null : datavalue1.Field<decimal>("Value"),
Series2 = cp == null ? (decimal?)null : cp.Field<decimal>("Value"),
};
foreach (var row in leftOuter)
{
DataRow dr = dtJoin.NewRow();
dr["DateOnly"] = row.Date;
dr["TimeOnly"] = row.Time;
if (row.ColumnA1 != null)
{
dr["ColumnA"] = row.Series1;
}
else
{
dr["ColumnA"] = DBNull.Value;
}
if (row.ColumnB != null)
{
dr["ColumnB"] = row.Series2;
}
else
{
dr["ColumnB"] = DBNull.Value;
}
dtJoin.Rows.Add(dr);
var leftOuter = from datavalue1 in dtA.AsEnumerable()
join datavalue2 in dtB.AsEnumerable()
on new { Date = datavalue1["Date"], Time = datavalue1["Time"] }
equals new { Date = datavalue2["Date"], Time = datavalue2["Time"] }
into resultset
from cp in resultset.DefaultIfEmpty()
select new
{
Date = datavalue1.Field<String>("Date"),
Time = datavalue1.Field<String>("Time"),
Series1 = datavalue1 == null ? (decimal?)null : datavalue1.Field<decimal>("Value"),
Series2 = cp == null ? (decimal?)null : cp.Field<decimal>("Value"),
};
foreach (var row in leftOuter)
{
DataRow dr = dtJoin.NewRow();
dr["DateOnly"] = row.Date;
dr["TimeOnly"] = row.Time;
if (row.ColumnA1 != null)
{
dr["ColumnA"] = row.Series1;
}
else
{
dr["ColumnA"] = DBNull.Value;
}
if (row.ColumnB != null)
{
dr["ColumnB"] = row.Series2;
}
else
{
dr["ColumnB"] = DBNull.Value;
}
dtJoin.Rows.Add(dr);
Wrting query for join between two data tables for Single Field
//---------------Wrting query for join between two data tables for Single Field---------------//
var result = from dataRows1 in dtJoiningWithTwoSeries.AsEnumerable()
join dataRows2 in dtTimeSeriesForCmbFinal.AsEnumerable()
on
dataRows1.Field<string>("DateOnly") equals dataRows2.Field<string>("Date")
select dtJoinForSingleField.LoadDataRow(new object[]
{
dataRows1.Field<string>("DateOnly"),
dataRows1.Field<string>("TimeOnly"),
dataRows1.Field<decimal>("Series 1"),
dataRows1.Field<decimal>("Series 2"),
dataRows2.Field<decimal>("Value"),
dataRows2.Field<string>("Date")
}, false);
//---------------copy output of result into datatable named 'dtJoinForSingleField'---------------//
dtJoinForSingleField = result.CopyToDataTable(); // This point records will be loaded in dtJoinForSingleField data table
var result = from dataRows1 in dtJoiningWithTwoSeries.AsEnumerable()
join dataRows2 in dtTimeSeriesForCmbFinal.AsEnumerable()
on
dataRows1.Field<string>("DateOnly") equals dataRows2.Field<string>("Date")
select dtJoinForSingleField.LoadDataRow(new object[]
{
dataRows1.Field<string>("DateOnly"),
dataRows1.Field<string>("TimeOnly"),
dataRows1.Field<decimal>("Series 1"),
dataRows1.Field<decimal>("Series 2"),
dataRows2.Field<decimal>("Value"),
dataRows2.Field<string>("Date")
}, false);
//---------------copy output of result into datatable named 'dtJoinForSingleField'---------------//
dtJoinForSingleField = result.CopyToDataTable(); // This point records will be loaded in dtJoinForSingleField data table
Switch Case in C#
switch (strTimeinterval)
{
case "Hour":
timeInterval = "1 Hour";
break;
case "Day":
timeInterval = "1 Day";
break;
case "Month":
timeInterval = "1 Month";
break;
case "Year":
timeInterval = "1 Year";
break;
default:
timeInterval = "10 Day";
break;
}
{
case "Hour":
timeInterval = "1 Hour";
break;
case "Day":
timeInterval = "1 Day";
break;
case "Month":
timeInterval = "1 Month";
break;
case "Year":
timeInterval = "1 Year";
break;
default:
timeInterval = "10 Day";
break;
}
Tuesday, 27 May 2014
how to find index number of selected value in combobox
int cmbAIndex = cmbA.FindStringExact(strCmbA);
Friday, 23 May 2014
how to get single Value from Linq to string in C#
var filteredSeries = (from s in dtSeriesWithMissVal.AsEnumerable()
where (s.Field<string>("Data Descriptor").Equals(strCmbMissValue))
select new{
seriesName = s.Field<string>("Series")}).Distinct();
string strSeries = filteredSeries.ElementAt(0).seriesName;
Thursday, 15 May 2014
Transfer Values from one form to other form
The Properties Approach
Properties allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method. In this method we are going to add one property to each form. In form1 we are going to use one property for retrieving value from the textbox and in form2, one property to set the label's text property. Then, in form1's button click event handler we are going to instantiate form2 and use the form2's property to set the label's text.
Follow the below steps:
Step 1: Add a property in form1 to retrieve value from textbox.
public string _textBox1
{
get{return textBox1.Text;}
}
Step 2: Add a property in form2 to set the labels' text
public string _textBox
{
set{label1.Text=value;}
}
Step 3: In form1's button click event handler add the following code.
private void button1_Click(object sender, System.EventArgs e)
{
Form2 frm=new Form2();
frm._textBox=_textBox1;
frm.Show();
}
Sunday, 11 May 2014
copies array to List: C#
using System; using System.Collections.Generic; class Program { static void Main() { int[] arr = new int[3]; // New array with 3 elements arr[0] = 2; arr[1] = 3; arr[2] = 5; List<int> list = new List<int>(arr); // Copy to List Console.WriteLine(list.Count); // 3 elements in List } } Output (Indicates number of elements.) 3
Saturday, 10 May 2014
Convert DataTable to List<> C#
public class ClsCountry
{
public int iCountryID { get; set; }
public string vchCountryName { get; set; }
public Nullable<bool> bActive { get; set; }
public string vchEntryDate { get; set; }
public string vchUpdateDate { get; set; }
}
//Method which will return List of Country type (class)
public static List<ClsCountryy> SelectAllCountries()
{
List<ClsCountry> lstCountry = new List<ClsCountry>();
DataTable dtCountries = new DataTable();
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter da = new SqlDataAdapter("select * from tblCountries", conn);
try
{
da.Fill(dtCountries);
}
catch
{
return lstCountry;
}
//DATATABLE TO LIST CONVERSION
foreach (DataRow dr in dtCountries.Rows)
{
lstmstCountry.Add(new ClsCountry
{
iCountryID = Convert.ToInt16(dr["iCountryID"]),
vchCountryName = dr["vchCountryName"].ToString(),
bActive = Convert.ToBoolean( dr["bActive"]),
vchEntryDate = dr["vchEntryDate"].ToString(),
vchUpdateDate = dr["vchUpdateDate"].ToString()
});
}
return lstCountry;
}
{
public int iCountryID { get; set; }
public string vchCountryName { get; set; }
public Nullable<bool> bActive { get; set; }
public string vchEntryDate { get; set; }
public string vchUpdateDate { get; set; }
}
//Method which will return List of Country type (class)
public static List<ClsCountryy> SelectAllCountries()
{
List<ClsCountry> lstCountry = new List<ClsCountry>();
DataTable dtCountries = new DataTable();
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter da = new SqlDataAdapter("select * from tblCountries", conn);
try
{
da.Fill(dtCountries);
}
catch
{
return lstCountry;
}
//DATATABLE TO LIST CONVERSION
foreach (DataRow dr in dtCountries.Rows)
{
lstmstCountry.Add(new ClsCountry
{
iCountryID = Convert.ToInt16(dr["iCountryID"]),
vchCountryName = dr["vchCountryName"].ToString(),
bActive = Convert.ToBoolean( dr["bActive"]),
vchEntryDate = dr["vchEntryDate"].ToString(),
vchUpdateDate = dr["vchUpdateDate"].ToString()
});
}
return lstCountry;
}
Convert DataTable to List<> C#
public class mCountry
{
public int iCountryID { get; set; }
public string vchCountryName { get; set; }
public Nullable<bool> bActive { get; set; }
public string vchEntryDate { get; set; }
public string vchUpdateDate { get; set; }
}
//Method which will return List of Country type (class)
public static List<Models.mCountry> SelectAllCountries()
{
List<Models.mCountry> lstmstCountry = new List<Models.mCountry>();
DataTable dtCountries = new DataTable();
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter da = new SqlDataAdapter("select * from mstCountries", conn);
try
{
da.Fill(dtCountries);
}
catch
{
return lstmstCountry;
}
//DATATABLE TO LIST CONVERSION
foreach (DataRow dr in dtCountries.Rows)
{
lstmstCountry.Add(new Models.mCountry
{
iCountryID = Convert.ToInt16(dr["iCountryID"]),
vchCountryName = dr["vchCountryName"].ToString(),
bActive = Convert.ToBoolean( dr["bActive"]),
vchEntryDate = dr["vchEntryDate"].ToString(),
vchUpdateDate = dr["vchUpdateDate"].ToString()
});
}
return lstmstCountry;
}
{
public int iCountryID { get; set; }
public string vchCountryName { get; set; }
public Nullable<bool> bActive { get; set; }
public string vchEntryDate { get; set; }
public string vchUpdateDate { get; set; }
}
//Method which will return List of Country type (class)
public static List<Models.mCountry> SelectAllCountries()
{
List<Models.mCountry> lstmstCountry = new List<Models.mCountry>();
DataTable dtCountries = new DataTable();
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter da = new SqlDataAdapter("select * from mstCountries", conn);
try
{
da.Fill(dtCountries);
}
catch
{
return lstmstCountry;
}
//DATATABLE TO LIST CONVERSION
foreach (DataRow dr in dtCountries.Rows)
{
lstmstCountry.Add(new Models.mCountry
{
iCountryID = Convert.ToInt16(dr["iCountryID"]),
vchCountryName = dr["vchCountryName"].ToString(),
bActive = Convert.ToBoolean( dr["bActive"]),
vchEntryDate = dr["vchEntryDate"].ToString(),
vchUpdateDate = dr["vchUpdateDate"].ToString()
});
}
return lstmstCountry;
}
How to convert a DataTable to list
DataTable dt = CreateDataTableInSomeWay();
List<DataRow> list = new List<DataRow>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr);
}
You can use GroupBy for that.
var groupedlist = list.GroupBy(c => c.Col1)
.Select((key, c) => new {Value = key, Count = c.Count()});
to count from a list of things.
You can do something like this to count from a list of things.
IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);
int count = methodNames.Where(x => names.Contains(x)).Count();
To count a single element
To count a single element
string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};
int count = words.Where(x => x.Equals(occur)).Count();
Insert update Delete with WCF in windowForm in C#
Step 1: Creating Database Table
- Database name: Registration
- Database table name: RegistrationTable
RegistrationTable Table
Step 2: Creating WCF Service
Now you have to create a WCF
Service:
- Go to Visual Studio 2010
- New -> Select a project
Now click on the project and
select WCF Service Application and provide a name for the service:
Now click on the Ok Button. Then
you will get the following 3 files in Solution Explorer:
- IService.cs
- Service.svc
- Service.svc.cs
The following image shows the
following files:
For inserting data into the database
you need to write the following code in the IService1.cs file
which contains the two sections:
- OperationContract
- DataContract
The OperationContract section is used to add service operations and a DataContract is used to add types to the service operations.
Iservice1.cs File
Now we create a function in the
OperationContract section of the Iservice1.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace WCFServiceForInsert
{
// NOTE: You can use
the "Rename" command on the "Refactor" menu to change the
interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
string InsertUserDetails(UserDetails userInfo);
[OperationContract]
DataSet SelectUserDetails();
[OperationContract]
bool DeleteUserDetails(UserDetails userInfo);
[OperationContract]
void UpdateRegistrationTable(UserDetails userInfo);
}
// Use a data
contract as illustrated in the sample below to add composite types to service
operations.
[DataContract]
public class UserDetails
{
int userid;
string username;
string password;
string country;
string email;
[DataMember]
public int UserID
{
get { return userid; }
set { userid = value; }
}
[DataMember]
public string UserName
{
get { return username; }
set { username = value; }
}
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[DataMember]
public string Country
{
get { return country; }
set { country = value; }
}
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
}
}
Service.svc.cs FileIn this file we define the definition of the functions for insert, update and delete.
And replace the code with the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace WCFServiceForInsert
{
public class Service1 : IService1
{
public DataSet SelectUserDetails()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User
ID=sa;Password=wintellect");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from RegistrationTable", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public void UpdateRegistrationTable(UserDetails userInfo)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial
Catalog=registration;User ID=sa;Password=wintellect");
con.Open();
SqlCommand cmd = new SqlCommand("update RegistrationTable set
UserName=@UserName,Password=@Password,Country=@Country, Email=@Email where
UserID=@UserID", con);
cmd.Parameters.AddWithValue("@UserID", userInfo.UserID);
cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
cmd.Parameters.AddWithValue("@Password", userInfo.Password);
cmd.Parameters.AddWithValue("@Country", userInfo.Country);
cmd.Parameters.AddWithValue("@Email", userInfo.Email);
cmd.ExecuteNonQuery();
con.Close();
}
public bool DeleteUserDetails(UserDetails userInfo)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial
Catalog=registration;User ID=sa;Password=wintellect");
con.Open();
SqlCommand cmd = new SqlCommand("delete from RegistrationTable where
UserID=@UserID", con);
cmd.Parameters.AddWithValue("@UserID", userInfo.UserID);
cmd.ExecuteNonQuery();
con.Close();
return true;
}
public string InsertUserDetails(UserDetails userInfo)
{
string Message;
SqlConnection con = new SqlConnection("Data Source=.;Initial
Catalog=registration;User ID=sa;Password=wintellect");
con.Open();
SqlCommand cmd = new SqlCommand("insert into
RegistrationTable(UserName,Password,Country,Email)
values(@UserName,@Password,@Country,@Email)", con);
cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
cmd.Parameters.AddWithValue("@Password", userInfo.Password);
cmd.Parameters.AddWithValue("@Country", userInfo.Country);
cmd.Parameters.AddWithValue("@Email", userInfo.Email);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = userInfo.UserName + " Details inserted successfully";
}
else
{
Message =
userInfo.UserName + " Details not inserted successfully";
}
con.Close();
return Message;
}
}
}
Testing the Service
Press F5 to run the service. A WCF Test Client form will be
displayed and it will load the service.
Now double-click the InserUserDetails() method under IService1. The InserUserDetails tab will be displayed.
Now right-click on the service1.vcs -> open in the browser:
Now copy the URL:
URL
http://localhost:2268/Service1.svc
Step 3: Create Windows Forms Application (Accessing the Service)
Now, you have to create a Windows Forms Application.
- Go to Visual Studio 2010
- New-> Select a project-> Windows Forms Application
- Click OK
Now add a new page to the website:
- Go to the Solution Explorer
- Right-click on the Project name
- Select add new item
- Add new windows form and give it a name
- Click OK
Now again go to the Solution Explorer and click on the add the service reference:
The following window will be opened:
Now paste the above URL in the address and click on the go Button:
Click on the Ok Button. Now the reference has been added in the Solution Explorer.
Now create a new Windows Form and drag and drop controls onto the Windows Form. Thedesigning form looks like below:
Double-click on the every Button, and add the following code with the click event handler:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
namespace WindowsFormsApplication1
{
public partial class Registration : Form
{
ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client(); // Add service reference
public Registration()
{
InitializeComponent();
showdata();
}
private void showdata() // To show the data in the DataGridView
{
DataSet ds = new DataSet();
ds = objService.SelectUserDetails();
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
private void button1_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails(); // Add type reference
objuserdetail.UserName = textBoxUserName.Text;
objuserdetail.Password = textBoxPassword.Text;
objuserdetail.Country = textBoxCountry.Text;
objuserdetail.Email = textBoxEmail.Text;
objService.InsertUserDetails(objuserdetail); // To insert the data
showdata();
}
private void button2_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
if (dataGridView1.Rows.Count > 1)
{
DataTable dt = new DataTable();
objuserdetail.UserID = (int)dataGridView1.CurrentRow.Cells[0].Value;
objService.DeleteUserDetails(objuserdetail); // To Delete the data
showdata();
}
}
private void Registration_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
int i = dataGridView1.SelectedCells[0].RowIndex;
textBoxUserName.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
textBoxPassword.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
textBoxCountry.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
textBoxEmail.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
ServiceReference1.UserDetails objuserdetail = new ServiceReference1.UserDetails();
objuserdetail.UserID = (int)dataGridView1.CurrentRow.Cells[0].Value;
objuserdetail.UserName = textBoxUserName.Text;
objuserdetail.Password = textBoxPassword.Text;
objuserdetail.Country = textBoxCountry.Text;
objuserdetail.Email = textBoxEmail.Text;
objService.UpdateRegistrationTable(objuserdetail); // To Update the
Data
showdata();
textBoxUserName.Text = "";
textBoxPassword.Text = "";
textBoxCountry.Text = "";
textBoxEmail.Text = "";
}
}
}
Now run the application
Press CTRL+F5 to run the application:
Now enter the UserName, Password, Country and Email and click
on the save Button:
Now click on the save Button. Data will be saved in the
database table and also displayed in the DataGridView on the form.
Now select a row from the DataGridView. Suppose we selected a
row which has the UserName monu and the userID 38.
Now click on the Delete Button to delete the row from the DataGridView
and database:
Now select a row from the DataGridView. Suppose we selected a
row which has the UserName Rohatash:
Now click on the edit Button to display row data in the
TextBoxes to update:
Now replace UserName Rohatash with Rohatash kumar and change
the country India to SriLanka:
Now click on the Update Button to update the data in the
DataGridView and the Database table. The updated row looks as in the
following image:
//ComboBox Binding Example
private void ComboBoxBind ()
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select empID,empname from
emp", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr
= dt.NewRow();
dr.ItemArray
= new object[] { 0, "---Select an item---" };
dt.Rows.InsertAt(dr,
0);
comboBox1.DisplayMember
= "empname";
comboBox1.ValueMember
= "empID";
comboBox1.DataSource
= dt;
con.Close();
}
Subscribe to:
Posts (Atom)