how can i select data from datatable - asp.net

My datatable contain column "Date" that have data like this in the following
'2013-01-01',
'2013-05-01',
'2014-01-01',
'2014-12-25',
'2014-12-26
But i want to get data something like 'select distinct year(Date)', and bind selected data into dropdownlist
however, syntax error message popup: "Syntax error: Missing operand after 'year' operator."
can I get any support? THANKS!!!!
private DataTable BuildDT(string [] date)
{
DataTable dt = new DataTable("test");
dt.Columns.Add("RowID", typeof(Int16));
dt.Columns.Add("Date", typeof(DateTime));
for (int i = 0; i < date.Length; i++)
{
dt.Rows.Add(i+1,date[i]); // {1,2013-01-01}
}
return dt;
}
private void ddlGetData2(DataTable table)
{
table.DefaultView.RowFilter = "distinct year(Date)";
DropDownList1.DataSource = table;
DropDownList1.DataBind();
}

You can do this with LINQ...
var years = table.AsEnumerable()
.Select(r => r.Field<DateTime>("Date").Year)
.Distinct()
.OrderBy(y => y)
.ToList();

You can use the .ToTable() on the associated DataView instance.
var dv = dt.DefaultView;
var distinctDates = dv.ToTable(true, "Date");

Related

How to pass parameters to Oracle DbContext FromSql in Net Core

var list = db.SomeModels.FromSql("select id from table1 where rownum < :r",10).ToList();
gives me
System.ArgumentException: 'Invalid parameter binding Parameter name: r'
What am I missing. Can't find any docs on that
The following should work:
var row = new OracleParameter("r", OracleDbType.Int32);
row.Value = 10;
var list = db.SomeModels
.FromSql("select id from table1 where rownum < :r", new object[] { row })
.ToList();
To add multiple parameters, add more OracleParameter objects to the object array:
var row = new OracleParameter("r", OracleDbType.Int32);
row.Value = 10;
var nameParameter = new OracleParameter("name", OracleDbType.Varchar2);
nameParameter.Value = "John";
var list = db.SomeModels
.FromSql("select id from table1 where rownum < :r and firstname = :name", new object[] { row, nameParameter })
.ToList();
Unfortunately, like yourself I haven't found any proper documentation for it. I will edit the answer when I do.
The following code will also work (tested with Oracle.ManagedDataAccess.Core v2.19.31 and Microsoft.EntityFrameworkCore v2.2.6):
var list = db.SomeModels
.FromSql("select id from table1 where rownum < {0}", 10)
.ToList()

Display result of linq query randomly in listview in Asp.net C#

var getquest = (from q in dc.Exam_Questions
where q.ExamNumber == int.Parse(Examnumber)
select new
{
QuestionTitle = q.QuestionTitle,
correctanswers = q.correctanswers,
ID = q.ID,
});
ListView1.DataSource = getquest;
ListView1.DataBind();
How to display result of linq query randomly in listview in Asp.net C#?
You can create a random data by adding a guid property to your query. After that you order the result by this new property.
var getquest = (from q in dc.Exam_Questions
where q.ExamNumber == int.Parse(Examnumber)
select new
{
RandomId = Guid.NewGuid(),
QuestionTitle = q.QuestionTitle,
correctanswers = q.correctanswers,
ID = q.ID,
});
ListView1.DataSource = getquest.OrderBy(p => p.RandomId).ToList();
ListView1.DataBind();

How to bind gridview with some conditions in asp.net?

DataTable dtbind = new DataTable();
dtbind = objvehicleBAL.GetTaxdetails();
for (int i = 0; i < dtbind.Rows.Count; i++)
{
DateTime dt1 = DateTime.ParseExact(dtbind.Rows[i]["todate"].ToString(), "dd/MM/yyyy", null);
if (dt1 < ((DateTime.Now.AddDays(15))))
{
GVTax.DataSource = dtbind.Rows[i];
GVTax.DataBind();
}
}
I had written my conditions in if(). I want to bind only satisfied rows in grid. How can I write this?
You do not need to bind the Grid in loop on the Row of data table rather filter the DataTable by the condition you want and bind it once. You can get DataView from the data table and use its property DataView.RowFilter to apply the date filter.
dtbind = objvehicleBAL.GetTaxdetails(); //Filter the record in GetTaxdetails
DataView dv = dtbind.DefaultView; //or use DataView with RowFilter
dv .RowFilter = "todate = #" + DateTime.Now.AddDays(15).ToString() + "#";
GVTax.DataSource = dv;
GVTax.DataBind();
DataTable dtbind1 = objvehicleBAL.GetTaxdetails();
DataTable dtbind2 = new DataTable();
foreach (DataRow row in dtbind1.Rows)
{
DateTime dt1 = DateTime.ParseExact(row["todate"].ToString(), "dd/MM/yyyy", null);
if (dt1 < ((DateTime.Now.AddDays(15))))
dtbind2.Rows.Add(row);
}
}
GVTax.DataSource = dtbind2;
GVTax.DataBind();
No need to bind each row and call DataBind mehtod each time.
Just use the following:
protected void BindGrid()
{
DataTable dtbind = new DataTable();
dtbind=objvehicleBAL.GetTaxdetails();//get the rows filtered in SQL
if(dtbind!=null && dtbind.Rows.Count>0)//always check for null for preventing exception
{
GVTax.DataSource = dtbind;
}
GVTax.DataBind();
}
Hope this helps you!
You can use the Select method of DataTable along with a filtering expression, to get the rows which match your criteria. Then, bind it to to your GridView.
string filterExp = "todate < dateadd(day,15,getdate())";
var filtered = dtBind.Select(filterExp);
GVTax.DataSource = filtered ;
GVTax.DataBind();
You can create another datatable and fill the rows satisfying your condition in the second datatable and bind your gridview with second datatable (having filtered rows)
dttableNew = dttableOld.Clone();
foreach (DataRow drtableOld in dttableOld.Rows)
{
if (/*put some Condition */)
{
dtTableNew.ImportRow(drtableOld);
}
}
GVTax.DataSource = dtTableNew;
GVTax.DataBind();

Copying one datatable selected column to another data table

I have a datatable, then I have all the column names of the datatable as checkbox, I want to display only those column records, for which user selected from the checkbox:
Below is the code, but I am not getting the desired result
var values = "";
string clmnm = "";
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected)
{
values += interestedIN.Items[i].Value + ",";
}
}
values = values.TrimEnd(',');
string[] words = values.Split(',');
DataTable dt = new DataTable();
dt = (DataTable)Session["dataset"];
DataTable dt1 = new DataTable();
foreach (string word in words)
{
dt1.Columns.Add(word, typeof(string));
if (clmnm == string.Empty)
{
clmnm = word.Trim();
}
else
{
clmnm += "," +word.Trim();
}
}
foreach (DataRow dr in dt.Rows)
{
string[] split = clmnm.Split(',');
int j =0;
string str = "";
string str2 = "";
while( j < split.Length)
{
str = split[j].ToString();
if (str2 == string.Empty)
{
str2 = "dr[\""+str.ToString()+"\"]";
}
else
{
str2 += "," + "dr[\""+str.ToString()+"\"]";
}
j+=1;
}
dt1.Rows.Add(str2);
}
then I am trying to export the result as an excel sheet: but getting the below excel sheet:
There is a lot of changes to be done to your code. Lets begin with selected columns from CheckBoxList. Try using List or Arrays to store which columns that user wants. Like
List<string> columns = new List<string>();
Then store the selected columns into the columns list. Then you need to add columns to your new DataTable dt1. As,
DataTable dt1 = new DataTable();
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected) //If user selected this columns checkbox.
{
columns.Add(interestedIN.Items[i].Text.Trim()); //Storing values to List.
dt1.Columns.Add(interestedIN.Items[i].Text.Trim()); //Adding columns to the DataTable.
}
}
Then you can loop through your original DataTable dt and store the values as below.
foreach (DataRow dr in dt.Rows)
{
DataRow dr1 = dt1.NewRow(); // Create new row which should have identical structure for inserting.
foreach(string col in columns)
{
dr1(col) = dr(col);
}
dt1.Rows.Add(dr1); //Add the row with the contents to the table.
}

Editable gridview based on list

Is it possible to create a gridview based on a list? I have the following list:
ID = 1
Name = John
Zip = 33141
ID = 2
Name = Tim
Zip = 33139
I want to be able to create an editable gridview with this list
When i bind it to the grid view, it seems to put everyting in one column, and i can't figure out how to get it to seperate it into different columns
Here is my code for setting the DataSource of the GridView:
DataTable table = ConvertListToDataTable(personList);
GridView1.DataSource = table;
GridView1.DataBind();
static DataTable ConvertListToDataTable(List<string> list)
{
// New table.
DataTable table = new DataTable();
// Get max columns.
int columns = 7;
// Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
// Add rows.
foreach (var rd in list)
{
table.Rows.Add(rd);
}
return table;
}
Here is an example:
private class Person
{
int m_iID;
string m_sName;
string m_sZip;
public int ID { get { return m_iID; } }
public string Name { get { return m_sName; } }
public string Zip { get { return m_sZip; } }
public Person(int iID, string sName, string sZip)
{
m_iID = iID;
m_sName = sName;
m_sZip = sZip;
}
}
private List<Person> m_People;
private void ConvertListToDataTable(List<Person> People)
{
DataTable table = new DataTable();
DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");
DataColumn col3 = new DataColumn("Zip");
col1.DataType = System.Type.GetType("System.String");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.String");
table.Columns.Add(col1);
table.Columns.Add(col2);
table.Columns.Add(col3);
foreach (Person person in People)
{
DataRow row = table.NewRow();
row[col1] = person.ID;
row[col2] = person.Name;
row[col3] = person.Zip;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}

Resources