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()
Related
Hey everyone I have the following code
Console.WriteLine("y: {0}", liveData.Tables["Players"].Rows.Count); //Shows full table
DataRow[] foundRows;
foundRows = liveData.Tables["Players"].Select("FName like 'Marc'");
foreach (DataRow dr in foundRows)
{
Console.WriteLine("Index is " + dr.Table.Rows.IndexOf(dr));
}
Now when i return my index of the row at variable dr that shows correctly
What i want to do is where it states Fname and Marc i want to pass those as variables and not manually input the string, is this possible?
Example, sometimes i may need to search Lname and whatever that is or a different first name?
Thank you for looking a bit stuck but again probably a simple answer :)
If I am not mistaken, you wish to have the query select a name from FName that resembles an input from an user (in this case 'Marc').
If thats the case, your best bet is to have something ask for the input beforehand and assign that value into a variable from a textbox for example.
String Queryname = TextBox1.Text
Console.WriteLine("y: {0}", liveData.Tables["Players"].Rows.Count); //Shows full table
DataRow[] foundRows;
foundRows = liveData.Tables["Players"].Select("FName like " + Queryname);
foreach (DataRow dr in foundRows)
{
Console.WriteLine("Index is " + dr.Table.Rows.IndexOf(dr));
}
Forgive me if I did not get your question. Let me know if that works and if not, try clarifying with an example.
string SelectQuery=//create query based on user input
foundRows = liveData.Tables["Players"].Select(SelectQuery);
For example if user wants to search based on Last Name, then Lname+ like + search term.You need to map the search attribute with column names.
Can't you just build the string with variables?: .Select(param+" like '"+value+"'")
You could create a function
public DataRow[] MySelect(string column, string name)
{
return liveData.Tables["Players"].Select(string.Format("{0} LIKE '{1}'", column, name));
}
And then use it like this
foundRows = MySelect("LName", "John");
I am iterating a DataTable in my C# code. I try to get the contents using of a column named "columnName" of row named "row" using -
object value = row["ColumnName"];
I get this error -
Error: System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.ArgumentException: Column 'FULL_COUNT' does not belong to table . at System.Data.DataRow.GetDataColumn(String columnName)
How is this possible ? My SQL query/result set has a column by that name and the query even runs in management studio.
How do I fix this error ?
I am guessing your code is iteration supposed to be something like this
DataTable table = new DataTable();
foreach (DataRow row in table.Rows) {
foreach (DataColumn col in table.Columns) {
object value = row[col.ColumnName];
}
}
If this is the case, row["ColumnName"] in each iteration looks for the same column with name ColumnName which obviously does not exists in your table.
The correct way is row[ColumnName] or row[col.ColumnName] in iteration above
I had a similar issue on my c# code, using a dataset which I had successfully initialized and populated with data from the DB.
So my return set was:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0]["systemLogo_img"]);
Of course the error was in t finding the column 'systemLogo_img'.
I noted that you simply do NOT have to call /qualify the column name. So the correction is:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0].ItemArray[0]);
Simply put: use "ItemArray" at position.
Thanks
Do not write Gridview column names instead of Database column names.
dataGridViewEmployeeClass.Rows[n].Cells[0].Value = item["write the Database Column names"].ToString();
Try this, make sure your column name is same
DataTable dt = new DataTable();
dt.Columns.Add("abc", typeof(string));
DataRow dr = dt.NewRow();
dr["abc"]="";
I had a similar issue which was very basic to fix.
I was querying with a specific column name rather than Select * (i.e. Select Title). Beginner's error but happens to everyone.
If you want to check if the column exists in the DataRow before accessing the value the following block can help...
if (dataRow.Table.Columns.Contains("theColumnName"))
{
// do work
string text = string.Empty;
if (dataRow["theColumnName"] != System.DBNull.Value)
{
text = Convert.ToString(dataRow["theColumnName"]);
}
}
If it doesn't exist and it needs to be added to the data table you can add the column using #Karthick Ganesan's example
// add a column
dataTable.Columns.Add("theColumnName", typeof(string));
I had same issue was trying to pass two different keys for same product.
item.Product = SqlHelper.GetSafeString(dr, "ProductName");
item.Product = SqlHelper.GetSafeString(dr, "Product");
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.
I have a DataTable dt with 2 columns. First col (call it CustomerId) is unique and doesn't allow nulls. the second one allows nulls and is not unique.
From a method I get a CustomerId and then I would like to either insert a new record if this CustomerId doesn't exist or increment by 1 what's in the second column corresponding to that CustomerId if it exists.
I'm not sure how I should approach this. I wrote a select statement (which returns System.Data.DataRow) but I don't know how to test whether it returned an empty string.
Currently I have:
//I want to insert a new row
if (dt.Select("CustomerId ='" + customerId + "'") == null) //Always true :|
{
DataRow dr = dt.NewRow();
dr["CustomerId"] = customerId;
}
If the datatable is being populated by a database. I would recommend making the customerid a identity column. That way when you add a new row it will automatically create a new customerid which will be unique and 1 greater than the previous id (depending on how you setup your identity column)
I would check the row count which is returned from the select statement. Something like
I would also use string.Format...
So it would look like this
var selectStatement = string.Format("CustomerId = {0}", customerId);
var rows = dt.Select(selectStatement);
if (rows.Count < 1){
var dr = dt.NewRow();
dr["CustomerId"] = customerId;
}
This is my method to solve similar problem. You can modify it to fit your needs.
public static bool ImportRowIfNotExists(DataTable dataTable, DataRow dataRow, string keyColumnName)
{
string selectStatement = string.Format("{0} = '{1}'", keyColumnName, dataRow[keyColumnName]);
DataRow[] rows = dataTable.Select(selectStatement);
if (rows.Length == 0)
{
dataTable.ImportRow(dataRow);
return true;
}
else
{
return false;
}
}
The Select Method returns an array of DataRow objects. Just check if its length is zero (it's never null).
By the way, don't write such statements in the code directly as in this example. There's a technique for breaching your code's security called "SQL Injection", I encourage you to read the Wikipedia Article. In brief, an experienced user could write SQL script that gets executed by your database and potentially do harmful things if you're taking customerId from the user as a string. I'm not experienced in database programming, this is just "general knowledge"...
Hi I have a DataSet and it has a table called Header. The Header table has a field called Long Agency Code. There is table called Wage that also has a field called Long Agency Code. I want to filter the Wage table based on the Long Agency Code available in Header Table. The following code snippet shows below:
DataTable dt = DataSet.Tables["Header"];
DataRowCollection headerRowCollection = dt.Rows;
foreach (DataRow headerRow in headerRowCollection)
{
FixedOutputter outputter = GetOutputter("Header", streamWriter);
MapElementCollection mapElementCollection = MapUtility.GetMapElementCollection(DataMap, "Header", DataMapFormatters);
outputter.OutputSingleRow(headerRow, mapElementCollection);
string filterExpression = "Long Agency Code == '" + headerRow["Long Agency Code"] + "'";
DataRow[] wageRowCollection = DataSet.Tables["Wage"].Select(filterExpression);
It blows up at the very last line with the message: "Syntax error: Missing operand after 'Agency' operator."
Surround Long Agency Code in [square brackets], and use a single = rather than ==.
Here is a decent reference: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx
What source did you use when coming up with Long Agency Code == '(something)' ? (It's wrong!)