by using datarow, insert a string value - c#

DataRow drEmpty = dsResult.Tables[1].NewRow();
dsResult.Tables[1].Rows.InsertAt(drEmpty, 0);
DataRow drBranch = dsResult.Tables[1].Rows[1];
drBranch[1] = "Branch"; <--error
dsResult.Tables[1].Rows.InsertAt(drBranch, 1);
my expected output for this few line of code is to add first empty row data into my dropdownlistbox and second row by adding "Branch" into the it but i failed to do so
Error msg given --
Input string was not in a correct format.Couldn't store in ows_ID Column. Expected type is Int64.
after that i try to change to
drBranch[1] = int64.Parse("Branch");
and i get another error
second error msg -- Input string was not in a correct format.
i get the answer that i want already, i will post the answer after 7 hours ,thanks all

In you example drBranch[1] represents the ows_ID column, which only accepts values of type integer. That means only numbers without a decimal point are allowed.
You could convert strings that contain numbers like "55" to an integer using Int64.Parse("55"), but you can't convert strings like "Branch" to integer. You're trying to store a string in the ows_ID column. Maybe you're trying to access the wrong index?

The problem is that "Branch" is not integer.
To cast a value into integer you need an integer value as a string like "526", "100".

I assume you think that the column ordinal is one-based but it's zero-based, hence drBranch[1] is the second column.
In my opinion it's better to use the column's name instead:
drBranch.SetField<String>("Branch", newBranch);
(i'm using the SetField extension method since it's strongly typed and supports nullables)

I would suggest using a DataTable before using DataRow:
DataTabel dtResult = dsResult.Tables[1].Clone();
dtResult.Columns[1].DataType = Type.GetType("System.String");
DataRow drEmpty = dtResult.NewRow();
dsResult.Tables[1].Rows.InsertAt(drEmpty, 0);
DataRow drBranch = dsResult.Tables[1].Rows[1];
drBranch[1] = "Branch";
dsResult.Tables[1].Rows.InsertAt(drBranch, 1);

Related

Using for nested loop, I want to fill my datable to another datatable

I want to add my dtbl data table record into my DtCloned data table, but after changing the type of column index 2 then fill it into dtCloned, I have an issue filling my record to dtcloned after changing the types.
DataTable dtCloned = dtbl.Clone();
dtCloned.Columns[2].DataType = typeof(TimeSpan);
for (int i = 1; i <= dtbl.Rows.Count; i++)
{
DataRow row = dtCloned.NewRow();
for (int j = 0; j < dtbl.Columns.Count; j++)
{
DataColumn dtc = new DataColumn();
if (j == 2)
{
//dtc.DataType = System.Type.GetType("System.Datetime");
//dtCloned.Columns.Add(dtc);
string s = dtbl.Rows[i][dtbl.Columns[j]].ToString();//12/31/1899 10:00:00 AM Tables[2].Rows[j][Model.Tables[2].Columns[i]]
string FTime;
FTime = s.Substring(11);
DateTime dt1 = Convert.ToDateTime(FTime.ToString());
string FTime2 = dt1.ToString("HH:mm:ss tt");
DateTime dt = DateTime.ParseExact(FTime2, "HH:mm:ss tt", null, DateTimeStyles.None);
string FTT = dt.ToString("HH:mm:ss");
row[i] = FTT;//DateTime.ParseExact(FTime, "HH:mm:ss tt", CultureInfo.InvariantCulture);
}
else
row[i] = dtbl.Rows[i][dtbl.Columns[j]];
}
dtCloned.ImportRow(row);
}
Have you considered just adding a new column to the dataTable pulled locally of the destination type expected, then do foreach() of every row and update the one column you wanted added.
dtbl.Columns.Add("YourTimeSpan", typeof(timespan));
foreach( DataRow dr in dtbl.Rows )
{
dr["YourTimeSpan"] = WhateverYouAreTryingToDo;
// the bulk of code that does all your date / tryparse conversion stuff.
}
So first, add the column of a time-stamp data type. Leaves original table alone so you dont have to duplicate everything. Now, by cycling through each DataRow in the DataTable, you have the row object.
By referencing the dr["YourTimeSpan"], you are referring to the column by its column name instead of ordinal representation. For your original data, if you know that column name you could refer to it that way too such as dr["OriginalDateTimeColumn"], but you could still do via dr[2] if you wanted to keep the 0-based ordinal column reference.
Now I am not sure what you are really doing. Trying to convert a string to a date/time based on known format? But if the original value of the cell IS a date/time, you should be able to work directly from it AS a datetime field and apply its normal .ToString() formatting options.
If you can EDIT YOUR EXISTING question with details of the original column data types, (string vs datetime), then you dont need to do conversions. If the originating data is coming from some SQL database, and the original data type is of a date/time or timestamp type of column, I would suggest adding the formatted value you want directly from the SQL engine vs you trying to keep parsing it here.
FEEDBACK
So, your existing table, column #3 (ordinal column 2 when zero-based) IS a date/time column. And you are just trying to convert it to a single string in 24-hr clock format? So 3:27pm = 15:27 via 24-hr clock?
Here is a sample of checking/confirming data type you are working with. I just put a breakpoint in the program when it got to my table and columns in-place and I added a blank row. So add to the watch window your "dtbl.Columns[2]" and expand it. Check to see/confirm if your column's data type is already that of DateTime structure. If so you don't need to do conversions.
If the value for the data type IS DateTime, and you only care about the string representation of it as 24hr, simple enough via the loop I has above, but instead, you would just add a column of a STRING data type, not timespan.
Then you could do
if( dr[2] is System.DBNull )
// no such value in the row date/time column
dr["YourTimeSpan"] = "";
else
// there IS a datetime value to work with.
// "HH" upper case is specifically 24-hr clock, then minute and second
dr["YourTimeSpan"] = dr[2].ToString("HH:mm:ss");
Note, that by this measure, it will have your extra column to the LAST column on the data row, but still simpler to work with than full cloning and doing crazy parse testing. Please let me know if helps and if you have any other issues.
If string is the final data type, just make sure you add the column as
dtbl.Columns.Add("YourTimeSpan", typeof(string));
instead of typeof(timespan) in the original example.

C# Filtering number on datagridview

I have a one textbox, one combobox and one datagridview and datagridview have some data on it.Combobox carry information about datagridview coloumn name.When I write text on textbox datagridview will be filtered according to column name which is in combobox.The code is given is not working when I try to write number on textbox It gave me error something like
'Cannot perform 'Like' operation on System.Double and System.String.'.
What I must do here for work.
string rowFilter = string.Format("[{0}] like '%{1}%'", combobox.Text, textBox1.Text);
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = rowFilter;
This is reasonable. You cannot apply the LIKE SQL operator to numbers.
You could fix this like below:
double number;
string rowFilter = double.TryParse(textBox1.Text, out number) ?
string.Format("[{0}]='{1}'", combobox.Text, textBox1.Text) :
string.Format("[{0}] like '%{1}%'", combobox.Text, textBox1.Text);
The method TryParse of double is used when we want from parsing a string to create a double. If this is possible, the string is the string representation of a double, then the method performs the conversion and returns true. The converted number is stored in out variable. While when the conversion fails, it returns false. Given that and using the ternary operator, ?, we can create the correct filter in all cases.

Input string was not in a correct format. C# error SQL database

I have a very BIG PROBLEM.
I want to delete a row from my database sql in C#.
here is my code:
int x = Convert.ToInt32(dataGridView1.SelectedCells[0].Value);
cmd.Parameters.Clear();
cmd.CommandText = "delete from Table2 where Name=#N";
cmd.Parameters.AddWithValue("#N", x);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
and finally im get a problem
Input string was not in a correct format.
Help me.
I get the error in first Line.
First problem:
dataGridView1.SelectedCells[0].Value is not a valid integer value, so Convert.ToInt32 fails.
Did you mean
string x = dataGridView1.SelectedCells[0].Value;
instead?
Second problem:
You are comparing the Name field to an integer value. I'm assuming Name is a _string_ value in the database (otherwise it's poorly named). When SQL looks for matching values, it will try to convert every value ofNamein the database to a number. if ANY value in theName` field is not a valid number, the query will fail.
I've read that null or empty string will return 0 (to be confirmed)
Here my guess :
Depending of your country, numbers should be wrote :
1.234
or
1,234
Solution
Hugly solution : You can simply do a :
Convert.ToInt32(dataGridView1.SelectedCells[0].Value.Replace(".",","));
Good solution : Or use Convert.ToInt32(String, IFormatProvider) :
Convert.ToInt32(dataGridView1.SelectedCells[0].Value,CultureInfo.CurrentCulture)
EDIT -1 without comment, i'm please to help.

How to add leading zeros in DataTable columns

I'm trying to add zeros in front of datatable column values if the lenght is less than 6 digits.
Ex: I have a column "SRNumber" in datatable with values 123, 2345, 56, 34523 etc and Would like to have my results like this 000123, 002345, 000056, 034523.
Note: I would like the manipulate the data in Datatable not in the sql query which retrieves the data. I have seen the solutions where we can add leading zeros to a string or variable but in mycase would like to do it for all the values in datatable columns.
ok, i figured it out with help of #eddie_cat answers. Here is what i did.
foreach (DataRow row in table.Rows)
{
row["SRNumber"] = row["SRNumber"].ToString().PadLeft(6, '0');
}
table.AcceptChanges();
Here, "SRNumber" is the column name in which i'm adding leading zero's. I hope this helps someone.
as eddie_cat said,
loop through the values and update the required fields
foreach(DataRow dr in mydatatable)
{
dr[myfield] = String.Format("{0:0000}", int.parse(dr[myfield]))
}
Note that you should first convert your string to int.
the example I've used int.parse(...) might throw an exception if dr[myfield] is dbnull.
I am not sure if you are looking for a SQL solution or a C# solution so I'll provide SQL since other have given you the C# solution:
UPDATE MYTABLE
SET SRNumber = RIGHT('000000' + SRNumber,6)
WHERE len(SRNumber) < 6

convert ds.Tables[1].Rows[0].ToString() to int

I can't convert ds.Tables[1].Rows[0].ToString() to an int.
ds.Tables[1].Rows[0] = 100;
Gives an error can't convert.
string test = Convert.Int32(ds.Tables[0].Rows[0]["YourIntegerColumn"].ToString())
If your column isnt an integer, then it's not gonna work, so you'll probly want to check if the column is null, then check if its parsable to an int using Int.TryParse
ds.Tables[1].Rows[0] returns a DataRow. You need to indicate the column that you want to assign the value:
ds.Tables[1].Rows[0]["Your column name"] = value;
Are you missing the column?
ds.Tables[1].Rows[0][column] = value;

Categories