The above error message appears when I am trying to get Column Value from Datatable.
This is what I find in the stacktrace:
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1
source)
and this in the TargetSite when debugging:
{ Boolean b__0(System.Data.DataRow)}
Here is my code:
DataTable hr = new DataTable();
hr.Columns.Add("BookingDate");
hr.Columns.Add("BookingId");
hr.Columns.Add("BookingSource");
hr.Columns.Add("CheckInDate");
hr.Columns.Add("CheckOutDate");
for (int i = 0; i < gmisc.GetModifiedBookings(gmoreq).Bookings.Length; i++)
{
hr.Rows.Add();
hr.Rows[i]["BookingDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingDate.ToString());
hr.Rows[i]["BookingId"] = Convert.ToInt64(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingId.ToString());
hr.Rows[i]["BookingSource"] = gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingSource.ToString();
hr.Rows[i]["CheckInDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].CheckInDate.ToString());
hr.Rows[i]["CheckOutDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].CheckOutDate.ToString());
}
Int64 BookingId = (from DataRow dr in hr.Rows
where (Int64)dr["BookingId"] == BookId
select (Int64)dr["BookingId"]).FirstOrDefault();
TextBox1.Text = Convert.ToString(BookingId);
Where did I go wrong, if somebody can please tell me.
Check your code, the very first two lines:
hr.Rows[i]["BookingDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingDate.ToString());
hr.Rows[i]["BookingId"] = Convert.ToInt64(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingId.ToString());
if gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingDate is null then ???
you are trying to convert it into string and then to datetime
if null then .ToString will give error "Specified cost......."
and same will happen at the time of converting to datetime.
If dr["BookingId"] is never null (otherwise add null check)
Use
Int64 BookingId = (from DataRow dr in hr.Rows
where Int64.Parse(dr["BookingId"].ToString()) ==BookId
select Int64.Parse(dr["BookingId"].ToString())).FirstOrDefault();
Instead of
Int64 BookingId = (from DataRow dr in hr.Rows
where (Int64)dr["BookingId"] == BookId
select (Int64)dr["BookingId"]).FirstOrDefault();
When you create a data column using the Add(string) overload, the type of the column is string (see http://msdn.microsoft.com/en-us/library/52xzw8tf.aspx). You cannot cast a string directly to Int64 or DateTime.
Use the Add(string, Type) overload or the Add(string, Type, string) overload to specify the type of the column's data.
Related
So i'm trying to filter my data with BindingSource from my datagridview
but my Column (Balance and Inactive Days) type is string also have Null value and i'm trying to use comparison operators <=, >=
but error shown System.Data.EvaluateException: 'Cannot perform '>=' operation on System.String and System.Int32.'
i've tried to change valueType of my datagridview,
dgv.Columns["Balance"].ValueType = typeof(Decimal); //it doesnt work
and tried to clone my datatable and set new type for my cloned datatable
DataTable dtCloned = dt.Clone();
dtCloned.Columns["Balance"].DataType = typeof(Decimal);
dtCloned.Columns["Inactive Days"].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
// error shown
System.ArgumentException: 'Input string was not in a correct format.Couldn't store <> in Debit Inactive Days Column. Expected type is Int32.'
Here is my filter code:
public void dgv_tabPage_content(DataGridView dgv, TabPage tabpage)
{
BindingSource bs = new BindingSource();
bs.DataSource = dgv.DataSource;
string filter_DD1 = "[Acct Type] LIKE '%DD%' AND [Balance] <= 6000.00 AND [Inactive Days] >= 5";
string filter_DD2 = "[Acct Type] LIKE '%DD%' AND [Balance] >= 6000.00 AND [Inactive Days] >= 3";
bs.Filter = string.Format("{1} OR {2}", filter_DD1, filter_DD2);
dgv.DataSource = bs;
}
How can i filter my string typed column with null value with comparison operators?
I'M not sure if that what you meant, but why not use where is not null and then your filter closure.
string filter = string.Format("[Task] is not null and LIKE '%{0}%'", tabpage.Text);
I think you mean to convert the type in the filter expression.
If this is what you mean, you can use the Convert function of the filter Expression: Convert(expression, type)
string filter_DD1 = "[Acct Type] LIKE '%DD%' AND Convert([Balance], System.Decimal) <= 6000.00 AND [Inactive Days] >= 5";
For more Info click here
Am trying to get a a Zero indexed Value from a column in the TableAdpter but it has refused , how can i retrieve a value in the Column index Zero , below is my code :
LoginTableAdapter l = new LoginTableAdapter();
string res = l.GetData("mueat", "1234").Rows[0].ToString();
And my table which is attached to the TableAdapter is as below , it's one column and i want to get the value t which is in a Zero index in the column access:
If we assume l.GetData("mueat", "1234") returns a DataTable, like so:
DataTable table = l.GetData("mueat", "1234"); // the dataTable
then this:
DataRow row = table.Rows[0]; // first row;
will only give you the first row out of the DataRowCollection's indexer
As we can see on the DataRow type, it has an indexer as well, giving access to the columns in the DataRow instance.
object columnValue = row[0]; // first column
You can now cast the object value to the correct type or call ToString on it to convert it to its string representation.
Putting this all back together in your compact one-liner you will get:
string res = l.GetData("mueat", "1234").Rows[0][0].ToString();
I'm trying to get record of a row using DataRow. Here's what I've done so far:
uID = int.Parse(Request.QueryString["id"]);
PhotoDataSetTableAdapters.MembersTableAdapter mem = new PhotoDataSetTableAdapters.MembersTableAdapter();
PhotoDataSet.MembersDataTable memTable = mem.GetMemberByID(uID);
DataRow[] dr = memTable.Select("userID = uID");
string uName = dr["username"].ToString();
Then I got the error:
Cannot implicitly convert type 'string' to 'int'
The error points to "username". I don't know what's wrong because I'm just trying to assign a string variable to a string value. Anyone figures out the reason of the error? Please help and thanks.
Change the following statement
DataRow[] dr = memTable.Select("userID = uID");
To
DataRow[] dr = memTable.Select("userID = "+ uID);
dr is a DataRow[] not a DataRow, therefor the compiler complains that you pass a String when he needs an int for the index.
You actually want the username of the the single DataRow in the DataTable, am i right?
String uName = memTable.AsEnumerable().Single().Field<String>("username");
Note that this throws an exception if there is more than one row in the DataTable. But since you pass an ID to the DataAdapter, i assume that it should return only one record.
Seems there are two problems. One is as Asif suggest that uID should be "userId = " + uID (should probably cast uID as string) and that dr is an array of datarows as Tim points out. You can access it by index too: dr[0]["userName"].ToString()
I have a datarow, but how can i convert it to an int ?
I tried this, but it doesn't work.
dsMovie = (DataSet)wsMovie.getKlantId();
tabel = dsMovie.Tables["tbl_klanten"];
eersteRij = tabel.Rows[0];
(Int32.Parse(eersteRij.ToString())
A DataRow is an object; it is not an integer. A DataRow contains one or more columns of data. You can index into the DataRow to access the values of these coulmns.
If table tbl_klanten contains one column, and that column is an integer, you can do the following:
var myInt = (int)eersteRij[0];
if the column is a string containing the value of an integer,
var myInt = int.Parse(eersteRij[0]);
If the column is named klant_id...
var myInt = (int)eersteRij["klant_id"];
if the column is a string containing the value of an integer,
var myInt = int.Parse(eersteRij["klant_id"]);
Simply use the Field method:
int result = row.Field<int>("ColName");
The Field method also supports nullable types:
The Field method provides support for accessing columns as nullable
types. If the underlying value in the DataSet is Value, the returned
nullable type will have a value of null.
And please notice:
The Field method does not perform type conversions. If type conversion is required, you should first obtain the column value by using the Field method. The column value should then be converted to another type.
Because even at that level of hierarchy you still have a DataRow and you can't convert a DataRow to int.. a value could be converted though.
And why are you converting whole DataRow to int.. usually you would like to get a value in a cell at a row so try, Somthing like this:
int value = (int)eersteRij.Items[0];
where 0 can be replaced by the cell position(int) or Column name(string)
You'll need to know which index the object you want is on, and cast that to an int, e.g.:
int value = (int)eersteRij[0];
DataSet dataSet = getDataFromDatabase();
DataRow tableRow = dataSet.Tables[0].Rows[0];
int valueAsInteger = Convert.ToInt32(tableRow["COLUMN_NAME"]);
I tend to use IndexOf() when looping thru the dataTable.
foreach (DataRow row in DataTable.table.Rows)
{
int index = dataTable.Rows.IndexOf(row);
}
I'm having problems when using linq on a datatable.asenumerable().
This throws InvalidCastException.
DateTime date=r.Field<DateTime>("date");
This works fine.
DateTime date = DateTime.Parse(r.Field<string>("date"));
What am I missing?
Regards Sven
Why would you expect it to work? The following code doesn't compile:
DateTime dt1 = (DateTime)"2004-01-01";
Whereas this does:
DateTime dt1 = DateTime.Parse("2004-01-01");
As in, you can't just cast a string to a DateTime, so if your value is a string, you need to explicitly convert it.
Are you sure your "date" column is of type DateTime?
This test code works as expected:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("date", typeof(DateTime)));
for (int i = 0; i < 10; i++)
{
DataRow row = dt.NewRow();
row["date"] = DateTime.Now.AddDays(i);
dt.Rows.Add(row);
}
foreach (var r in dt.AsEnumerable())
{
DateTime d = r.Field<DateTime>("date"); // no problems here!
Console.Write(d.ToLongDateString());
}
Cast works between related types. string and date don't belong to same hierarchy & hence no direct translation is possible.
You can use cast, when you are sure that the types are related and conversion is possible.
Parse is different than cast.
i.e you are telling the runtime to see if it can be parsed to make a date out of it (per your example).