Select 2 or more columns on DataTable using LINQ - c#

I have a DataTable and I want to select multiple columns on the DataTable that matches the input in the textbox. The code below only selects 1 column.
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select data.Field<string> ("Description");
foreach (var res in result) {
txtxDescription.Text = res.ToString ();
}
How can I select 2 or more columns on DataTable using LINQ?

why not select full rows (DataRow object) and then take all necessary values from them?
var rows = mDataTable.AsEnumerable()
.Where(data => data.Field<string>("Code") == txtCode.Text);
foreach(DataRow r in rows)
{
txtxDescription.Text = r.Field<string>("Description");
}
another option is to project data to anonymous objects:
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select new
{
Description = data.Field<string> ("Description"),
Code = data.Field<string> ("Code")
};
foreach (var res in result)
{
// last value always replace `txtxDescription.Text` ??
txtxDescription.Text = res.Description;
txtxCode.Text = res.Code;
}

public void GridviewBinding()
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["SQLMSDB"].ConnectionString;
string sql = "select * from tbl_users";
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
gridviewcontrol.DataSource = ds;
gridviewcontrol.DataBind();
ViewState["GridViewBindingData"] = ds.Tables[0];
}
}
}
}
protected void btn_searching_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txt_search.Text.Trim().ToString()) || !String.IsNullOrWhiteSpace(txt_search.Text.Trim().ToString()))
{
DataTable dt = (DataTable)ViewState["GridViewBindingData"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<dynamic>("UserName") == txt_search.Text);
DataTable dt2 = dataRow.CopyToDataTable<DataRow>();
gridviewcontrol.DataSource = dt2;
gridviewcontrol.DataBind();
}
else
{
GridviewBinding();
}
}

Related

only 1 record coming instead of multiple records in the model in c#

im getting only 1 row multiple times instead of getting multiple records. same record getting multiple times in the datatable and model.
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT
Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
m.DeviceDate =Convert.ToDateTime(deviceDate);
m.Units =Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);
Since the object is created before foreach, The object will be replaced with new entries all the time. Add Trans_energycons_ReportModel m = new Trans_energycons_ReportModel(); inside foreach
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
//Create object here
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
m.DeviceDate = Convert.ToDateTime(deviceDate);
m.Units = Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);

DataTable To Load A List

I've created a stored procedure (SP) and integrated that in the following way that works just fine:
Edited:
private DataTable GetSPResult()
{
int m = Convert.ToInt32(DropDownList1.SelectedValue);
int k = Convert.ToInt32(DropDownList2.SelectedValue);
DataTable ResultsTable = new DataTable();
var context = new DemoEntities();
var con = context.Database.Connection;
var connectionState = con.State;
try
{
using (context)
{
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "MonthlyConsumption"; //Here is the SP
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Para1", SqlDbType.Int));
cmd.Parameters["#Para1"].Value = m;
cmd.Parameters.Add(new SqlParameter("#Para2", SqlDbType.Int));
cmd.Parameters["#Para2"].Value = k;
using (var reader = cmd.ExecuteReader())
{
ResultsTable.Load(reader);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (con != null)
{
con.Close();
}
}
return ResultsTable;
}
Finally done the below: On button click, I am able to see data in the report
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = GetSPResult();
ReportViewer1.Visible = true;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("Report1.rdlc");
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", dt));
}
Output:
But when I try to convert a list to DataTable with ORM, it throws no exception but no data in the report as follows:
Output:
This is the code that I've done so far with ORM - Entity Framework that also works: By the way, I put breakpoint for debugging purpose and it gets the value but doesn't return data in the report
public DataTable GetSPResult()
{
int m = Convert.ToInt32(DropDownList1.SelectedValue);
int k = Convert.ToInt32(DropDownList2.SelectedValue);
DataTable ResultsTable = new DataTable();
var context = new DemoEntities();
using (context)
{
var query = context.MonthlyConsumption(m, k).ToList();
foreach (var item in query)
{
ResultsTable.Columns.Add("Store");
ResultsTable.Columns.Add("Product");
ResultsTable.Columns.Add("Jan");
ResultsTable.Columns.Add("Feb");
ResultsTable.Columns.Add("Mar");
ResultsTable.Columns.Add("Apr");
ResultsTable.Columns.Add("May");
ResultsTable.Columns.Add("Jun");
ResultsTable.Columns.Add("Jul");
ResultsTable.Columns.Add("Aug");
ResultsTable.Columns.Add("Sep");
ResultsTable.Columns.Add("Oct");
ResultsTable.Columns.Add("Nov");
ResultsTable.Columns.Add("Dec");
ResultsTable.Rows.Add(item.StoreName);
ResultsTable.Rows.Add(item.ItemName);
ResultsTable.Rows.Add(item.M1.Value);
ResultsTable.Rows.Add(item.M2.Value);
ResultsTable.Rows.Add(item.M3.Value);
ResultsTable.Rows.Add(item.M4.Value);
ResultsTable.Rows.Add(item.M5.Value);
ResultsTable.Rows.Add(item.M6.Value);
ResultsTable.Rows.Add(item.M7.Value);
ResultsTable.Rows.Add(item.M8.Value);
ResultsTable.Rows.Add(item.M9.Value);
ResultsTable.Rows.Add(item.M10.Value);
ResultsTable.Rows.Add(item.M11.Value);
ResultsTable.Rows.Add(item.M12.Value);
}
}
return ResultsTable;
}
Note and Updated: Could I convert the List to a IDataReader to load it or is there any simple way to make it done? I've seen some of the tutorials where the author has used foreach loop to iterate the list and then bind it to the DataTable. But I am just trying to simply load the list to the DataTable.
Finally got it done. Just converted the list to DataTable using the following method:
public DataTable ToDataTable<T>(List<T> items)
{
DataTable ResultsTable = new DataTable(typeof(T).Name);
//Gets all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Sets column names as Property names
ResultsTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//Inserts property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
ResultsTable.Rows.Add(values);
}
return ResultsTable;
}

how to display comparison chart using ajax

I am trying to display ajax bar chart in my web page. But it is only displaying one value .
My db contains 3 columns(name, credit, debit) I want to display the credit debit values in chart. But the chart is only displaying one value. How can I modify the given below coding. Thank you.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if (prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "select Name, Debit, Credit From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#name", SqlDbType.NVarChar);
prms[0].Value = ddlCountries.SelectedItem.Value.ToString();
DataTable dt = GetData(query, prms);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} -RunTimeReportChart", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
Data Base:
Actual Output:
The given below chart is only displaying the name and debit value. I want to display the credit value also. Please help me.
Something Like :
decimal[] z = new decimal[dt.Rows.Count];
z[i] = Convert.ToInt32(dt.Rows[i][2]);
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = z });

Where should i put my C# if statement, for the case my sql query comes back blank?

Where can i put an if-statement saying that: if the sql query comes back empty, then Console.WriteLine("I'm sorry, empty...whatnot");
I don't know how to check to see if the result of the query is empty.
This is my code:
public void IsMovieInStore()
{
Console.Write("Searh for a movie title: ");
string title = Console.ReadLine();
string connectionString = #"Data Source=|DataDirectory|\VideoStoreDB.sdf";
SqlCeConnection connection = new SqlCeConnection(connectionString);
SqlCeCommand command = new SqlCeCommand("SELECT Movie.Title, MovieHandler.InStore FROM Movie INNER JOIN MovieHandler ON Movie.MovieCodeLable = MovieHandler.MovieCodeLable WHERE MovieHandler.InStore = 1 AND Movie.Title = #title", connection);
command.Parameters.AddWithValue("#title", title);
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Movie");
foreach (DataTable dataTable in dataSet.Tables)
{
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
Console.WriteLine(column.ColumnName + ": " + row[column]);
}
Console.WriteLine("-------------------------");
}
}
Console.ReadLine();
}
You can easily check this by assigning dataAdapter.Fill(dataSet, "Movie"); to an int variable. The Fill method returns the number of rows that are added to or refreshed in the dataset. See msdn for more information: DataAdapter.Fill Method.
int rows = dataAdapter.Fill(dataSet, "Movie");
if(rows > 0)
{
//process data
}
else
{
Console.WriteLine("Sorry, no data...");
}
try checking table and row counts
//....
dataAdapter.Fill(dataSet, "Movie");
if (0 == dataSet.Tables.Count || 0 == dataSet.Tables[0].Rows.Count)
{
Console.WriteLine("I'm so lonely");
}
foreach (DataTable dataTable in dataSet.Tables)
//...
You dont need to use dataset, use datatable:
public void IsMovieInStore()
{
Console.Write("Searh for a movie title: ");
string title = Console.ReadLine();
string connectionString = #"Data Source=|DataDirectory|\VideoStoreDB.sdf";
SqlCeConnection connection = new SqlCeConnection(connectionString);
SqlCeCommand command = new SqlCeCommand("SELECT Movie.Title, MovieHandler.InStore FROM Movie INNER JOIN MovieHandler ON Movie.MovieCodeLable = MovieHandler.MovieCodeLable WHERE MovieHandler.InStore = 1 AND Movie.Title = #title", connection);
command.Parameters.AddWithValue("#title", title);
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
If(dataTable != null && dataTable.Rows.Count>0)
{
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
Console.WriteLine(column.ColumnName + ": " + row[column]);
}
Console.WriteLine("-------------------------");
}
}
}
else{
Console.WriteLine("Empty result");
}
Console.ReadLine();
}

Add an item to combobox before binding data from the database

I had a combobox in a Windows Forms form which retrieves data from a database. I did this well, but I want to add first item <-Please select Category-> before the data from the database. How can I do that? And where can I put it?
public Category()
{
InitializeComponent();
CategoryParent();
}
private void CategoryParent()
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category, Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
}
}
You could either add the default text to the Text property of the combobox like this (preferred):
CBParent.Text = "<-Please select Category->";
Or, you could add the value to the datatable directly:
da.Fill(dt);
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;
public class ComboboxItem
{
public object ID { get; set; }
public string Name { get; set; }
}
public static List<ComboboxItem> getReligions()
{
try
{
List<ComboboxItem> Ilist = new List<ComboboxItem>();
var query = from c in service.Religions.ToList() select c;
foreach (var q in query)
{
ComboboxItem item = new ComboboxItem();
item.ID = q.Id;
item.Name = q.Name;
Ilist.Add(item);
}
ComboboxItem itemSelect = new ComboboxItem();
itemSelect.ID = "0";
itemSelect.Name = "<Select Religion>";
Ilist.Insert(0, itemSelect);
return Ilist;
}
catch (Exception ex)
{
return null;
}
}
ddlcombobox.datasourec = getReligions();
CBParent.Insert(0,"Please select Category")
You should add "Please select" after you bind data.
var query = from name in context.Version
join service in context.Service
on name.ServiceId equals service.Id
where name.VersionId == Id
select new
{
service.Name
};
ddlService.DataSource = query.ToList();
ddlService.DataTextField = "Name";
ddlService.DataBind();
ddlService.Items.Insert(0, new ListItem("<--Please select-->"));
There are two quick approaches you could try (I don't have a compiler handy to test either one right now):
Add the item to the DataTable before binding the data.
You should be able to simply set CBParent.Text to "<- Please Select Category ->" after you bind the data. It should set the displayed text without messing with the items.
void GetProvince()
{
SqlConnection con = new SqlConnection(dl.cs);
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT ProvinceID, ProvinceName FROM Province", con);
DataTable dt = new DataTable();
int i = da.Fill(dt);
if (i > 0)
{
DataRow row = dt.NewRow();
row["ProvinceName"] = "<-Selecione a Provincia->";
dt.Rows.InsertAt(row, 0);
cbbProvince.DataSource = dt;
cbbProvince.DisplayMember = "ProvinceName";
cbbProvince.ValueMember = "ProvinceID";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources