How to Send bytes array in dataset and read from it - c#

I want to send bytes in a data set and I have a column of data type varbinary(MAX). When i try to send a byte array, instead of showing a byte array in the data set it shows the below data. I don't know if it is a pure byte array or if it is showing bytes. What I was thinking the "ProjectIcons" column should return was a value like {bytes[1305]}....
1)If it is bytes then how can i read the bytes from dataset.
Please let me know where I am wrong. I am using below code:
public DataSet GetAllProjectStandardIcons2()
{
var images = (from p in dbModel.tbl_STANDARDPROJECTICONS select new ProjectDetails1
{
id = p.id,
ProjectIcons = (Byte[])(p.ProjectIcons)
}).ToList();
DataTable dt = new DataTable();
if (images.Count > 0)
{
Byte[] ProjectIcons;
DataColumn dc = new DataColumn("id");
DataColumn dc1 = new DataColumn("ProjectIcons");
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
for (var i = 0; i < images.Count(); i++)
{
DataRow row = dt.NewRow();
row["id"] = images[i].id;
ProjectIcons = (Byte[])images[i].ProjectIcons;
row["ProjectIcons"] = ProjectIcons;
dt.Rows.Add(row);
}
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}

please try to Save image in Base64 Format and retrieve in same format, after that try to convert it in bytes...try following code
for (var i = 0; i < images.Count(); i++)
{
DataRow row = dt.NewRow();
row["id"] = images[i].id;
row["ProjectIcons"] = Convert.ToBase64String(images[i].ProjectIcons);//convert here byte array to base64
dt.Rows.Add(row);
}

I have found the solution Need to convert bytearray to base64 array below is the code that is working for me
public DataSet GetAllProjectStandardIcons2()
{
var images = (from p in dbModel.tbl_STANDARDPROJECTICONS
select new ProjectDetails1
{
id = p.id,
ProjectIcons = (Byte[])(p.ProjectIcons)
}).ToList();
DataTable dt = new DataTable();
if (images.Count > 0)
{
Byte[] ProjectIcons;
DataColumn dc = new DataColumn("id");
DataColumn dc1 = new DataColumn("ProjectIcons");
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
for (var i = 0; i < images.Count(); i++)
{
DataRow row = dt.NewRow();
row["id"] = images[i].id;
row["ProjectIcons"] = Convert.ToBase64String(images[i].ProjectIcons);//convert here byte array to base64
dt.Rows.Add(row);
}
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}

Related

Creating DataTable from Text File and splitting

This is going to be my text file (30 lines)
OrderNo:37374
OrderQuantity:250
BarcodeQR:584,25478Klkd28
NormalBarcode:1565484864
.......
.......
.......
This is the code :
public DataTable DTforReport()
{
DataTable dt = new DataTable();
DataColumn col = new DataColumn("test");
col.DataType = System.Type.GetType("System.String");
dt.Columns.Add(col);
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
foreach (var line in lines)
{
var segments = line.Split(';');
foreach (var seg in segments)
{
DataRow dr = dt.NewRow();
dr[0] = seg;
dt.Rows.Add(dr);
}
}
return dt;
}
I want my output like this
OrderNo OrderQuantity BarcodeQR
37374 250 584,25478Klkd28
How can I change my code to achieve this?
You have generated only one column. Change your code like below to see your desired result:
public DataTable DTforReport()
{
DataTable dt = new DataTable();
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
DataRow dr = dt.NewRow();
for (int i = 0; i < lines.Length; i++)
{
DataColumn col = new DataColumn(lines[i].Split(':')[0]);
col.DataType = Type.GetType("System.String");
dt.Columns.Add(col);
var segment = lines[i].Split(':')[1];
dr[i] = segment;
}
dt.Rows.Add(dr);
return dt;
}
I suggest you to modify your method like the following:
public DataTable DTforReport()
{
DataTable testTable = new DataTable("Test");
testTable.Columns.Add("OrderNo");
testTable.Columns.Add("OrderQuantity");
testTable.Columns.Add("BarcodeQR");
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
foreach (var line in lines)
{
DataRow dRow = testTable.NewRow();
var segments = line.Split(';');
for (int i = 0; i < segments.Length; i++)
{
var colValues = segments[i].Split(':');
dRow[i] = colValues[1];
}
testTable.Rows.Add(dRow);
}
return testTable;
}
Few suggestions for improvement:
I have given static column names, if you want to add more or they may change in future means you can create dynamic columns in the datatable.
If you have doubts in the input values, make use of proper validation
Validations in the sense, make sure about the splitted values before accessing them through index otherwise they may ends up with IndexOutOfRangeException
DataTable dt = new DataTable();
string[] lines = File.ReadAllLines("C:\\Users\\abc\\Desktop\\abc.txt");
var firstLine = lines.First();
var columns = firstLine.Split(';');
for (var icount = 0; icount < columns.Count(); icount++)
{
var colName = columns[icount].Contains(":") ? columns[icount].Split(':')[0] : "Column" + icount;
var dataCol = new DataColumn(colName);
dataCol.DataType = System.Type.GetType("System.String");
dt.Columns.Add(dataCol);
}
foreach (var line in lines)
{
DataRow dr = dt.NewRow();
var segments = line.Split(';');
for (var icount = 0; icount < segments.Count(); icount++)
{
var colVal = segments[icount].Contains(":") ? segments[icount].Split(':')[1] : "";
dr[icount] = colVal;
}
dt.Rows.Add(dr);
}
*Number of column must be same in each row.

Why does SqlDataAdapter's fill not allow me to add a row with the same its own rows' value as appearance?

Why does SqlDataAdapter's Fill method not allow me to add a row with the same its own rows' value as appearance? I could not success to provide a row's value that appears at the same row with filled one in DataTable.
Check this out:
using (SqlDataAdapter a = new SqlDataAdapter("SELECT SIPNO, SERINO, TARIH FROM SNOHAREKETLER WHERE Cast(TARIH as DATE) BETWEEN '2015/03/19' AND '2015/03/20' AND (TEZNO = 'T23' OR TEZNO = 'T31') AND CIKTI is null", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
t.Columns.Add("MyColumn", typeof(string));
DataRow workRow;
int iGetCount = t.Rows.Count;
for (int i = 0; i <= iGetCount - 1; i++)
{
workRow = t.NewRow();
workRow["MyColumn"] = i;
t.Rows.Add(workRow);
}
// 4
// Render data onto the screen
dataGridView1.DataSource = t;
}
Here is the solution of my issue. I searched and consulted someone. My issue was trying to add a NewRow and this causes the issue.
DataTable t = new DataTable();
a.Fill(t);
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
t.Columns.Add(newCol);
foreach (DataRow row in t.Rows)
{
row["NewColumn"] = "With String";
}
dataGridView1.DataSource = t;

Losing data and gridview C#

I have a program by VC2008 that send dataTable I sended it using the constractor I solve it help at losing data entered in dataview C# - to datagridview in another Form it work fine but I want to send only the new row I tried to copy using ImportRrow it to another datatable but it gives Form2 Blank.
and I send the data as datatable by method as following:
public DataTable showout2()
{
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
DataColumn dc4 = new DataColumn("المالك");
DataColumn dc5 = new DataColumn("قيمة");
DataColumn dc6 = new DataColumn("نوع العملة");
DataColumn dc7 = new DataColumn("الدائن");
DataColumn dc8= new DataColumn("المدين");
DataColumn dc9= new DataColumn("تاريخ");
DataColumn dc10 = new DataColumn("تفاصيل");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
dtab.Columns.Add(dc4);
dtab.Columns.Add(dc5);
dtab.Columns.Add(dc6);
dtab.Columns.Add(dc7);
dtab.Columns.Add(dc8);
dtab.Columns.Add(dc9);
dtab.Columns.Add(dc10);
DateTime date = new DateTime();
date = DateTime.Now;
// Create an array for the values.
object[] newRow = new object[10];
Set the values of the array.
string s = numb.Text;
newRow[0] = numb.Text;
newRow[1] = Account_numb.Text;
newRow[2] = Account_nam.Text;
newRow[3] = owner.Text;
newRow[4] = curency.Text;
newRow[5] = comboBox1.Text;
newRow[6] = Depet.Text;
newRow[7] = cridet.Text;
newRow[8] = date.ToString();
newRow[9] = note.Text;
declare DataRow and adding it to DataTable
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
I transfer the data from Form as following
cashagree fm = cashagree(shouwout2());
I copy the datarow in constractor take datatable as prameter as following:
public Cashagree(DataTable d2)
{
dt.ImportRow(d2.Rows[0]);
}
here I assign the datasource and mange the secound datagridview
private void Cashagree_Load_1(object sender, EventArgs e)
{
try
{
for (int i = 0; i != dt.Rows.Count; i++){
label1.Text= dt.Rows[i].ToString();
if (string.IsNullOrEmpty(dt.Rows[i].ToString()))
{
MessageBox.Show("This is empty");
}
}
dataGridView.DataSource = dt;
dataGridView.Columns[3].Visible = false;
dataGridView.Columns[4].Visible = false;
dataGridView.Columns[5].Visible = false;
dataGridView.Columns[6].Visible = false;
dataGridView.Columns[7].Visible = false;
}
catch (Exception w) { MessageBox.Show("Error" + w.StackTrace); }
}
thank you for helping

Convert resultset in to Datatable [duplicate]

This question already has answers here:
Best Practice: Convert LINQ Query result to a DataTable without looping
(5 answers)
Closed 8 years ago.
How can I convert the result of a LINQ query where I select some columns of a DataTable to a DataTable again?
DataTable dtN = new DataTable();
dtN.Columns.Add("Id");
dtN.Columns.Add("Name");
dtN.AcceptChanges();
for (int i = 1; i <= 10; i++)
{
DataRow dr = dtN.NewRow();
dr["Id"] = i;
dr["Name"] = "A"+i.ToString();
dtN.Rows.Add(dr);
dtN.AcceptChanges();
}
var data = from r in dtN.AsEnumerable()
select new { Name = r["Name"].ToString() };
//this line is giving error because CopyToDatatable is not available
DataTable dt = data.CopyToDataTable();
DataTable dtN = new DataTable();
dtN.Columns.Add("Id");
dtN.Columns.Add("Name");
dtN.AcceptChanges();
for (int i = 1; i <= 10; i++)
{
DataRow dr = dtN.NewRow();
dr["Id"] = i;
dr["Name"] = "A" + i.ToString();
dtN.Rows.Add(dr);
dtN.AcceptChanges();
}
var data = from r in dtN.AsEnumerable()
select new { Name = r["Name"].ToString() };
DataTable dt = new DataTable();
dt.Columns.Add("Name");
foreach(var s in data)
{
DataRow dr = dt.NewRow();
dr["Name"] = s.Name;
dt.Rows.Add(dr);
dt.AcceptChanges();
}
//DataTable dt = data.CopyToDataTable();
EDIT :
CopyToDataTable() is only available on IEnumerable<T> where T is or derives from DataRow.
So in your first case var data=from r in dtN.AsEnumerable() select r;
CopyToDataTable() is available because your query returns an IEnumerable<'DataRow> .
But in the second case var data = from r in dtN.AsEnumerable() select new { Name = r["Name"].ToString() };
you are returning an anonymous type.
Anonymous types don't carry the extension method for CopyToDataTable().
If you wish to convert a non-datatable-derived T to a datatable, MSDN has a sample class that reflects out any type and performs the conversion .Please Read this link
If you have a DataTable with a lot of columns:
var dt = new DataTable();
dt.Columns.Add("Foo", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Bar", typeof(int));
dt.Rows.Add(new object[]{"Foo", "Max", 555});
dt.Rows.Add(new object[]{"Blub", "Marry", 123});
dt.Rows.Add(new object[]{"Bla", "Mac", 999});
but you're only interested in a DataTable in one or some of the columns, but not all, you can simply use a DataView:
var nameOnlyTable = new DataView(dt).ToTable(false, new []{"Name"});
No need for LINQ.

Convert datatable to datareader

For Performance improvement I want to convert datatable to datareader. I can not do that through query. So is there any other way to do so?
I know this is old, but the answers here seem to have missed the point of the OPs question.
DataTables have a method called CreateDataReader which will allow you to convert a DataTable to a DbDataReader object. In this case a DataTableReader.
DataTable table = new DataTable();
//Fill table with data
//table = YourGetDataMethod();
DataTableReader reader = table.CreateDataReader();
I should point out that this will not increase performance since you should be using one or the other.
Here are some more resources on the matter:
DataReader Vs DataTable
Is datareader quicker than dataset when populating a datatable?
For example
public DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
DataTable datatable = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();
try
{
foreach (DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = myRow.GetType();
myDataColumn.ColumnName = myRow[0].ToString();
datatable.Columns.Add(myDataColumn);
}
while (dataReader.Read())
{
DataRow myDataRow = datatable.NewRow();
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
myDataRow[i] = dataReader[i].ToString();
}
datatable.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
return datatable;
}
catch (Exception ex)
{
Error.Log(ex.ToString());
return datatable;
}
}
Use DataTable constructor,
DataTable table = new DataTable();
//Fill table with data
DataTableReader reader = new DataTableReader(table);
Good Look!
public DataTable GetTable(IDataReader _reader)
{
DataTable dataTable1 = _reader.GetSchemaTable();
DataTable dataTable2 = new DataTable();
string[] arrayList = new string[dataTable1.Rows.Count];
for (int i = 0; i < dataTable1.Rows.Count; i++)
{
DataColumn dataColumn = new DataColumn();
if (!dataTable2.Columns.Contains(dataTable1.Rows[i]["ColumnName "].ToString()))
{
dataColumn.ColumnName = dataTable1.Rows[i]["ColumnName "].ToString();
dataColumn.Unique = Convert.ToBoolean(dataTable1.Rows[i]["IsUnique "]);
dataColumn.AllowDBNull = Convert.ToBoolean(dataTable1.Rows[i]["AllowDBNull "]);
dataColumn.ReadOnly = Convert.ToBoolean(dataTable1.Rows[i]["IsReadOnly "]);
dataColumn.DataType = (Type)dataTable1.Rows[i]["DataType "];
arrayList[i] = dataColumn.ColumnName;
dataTable2.Columns.Add(dataColumn);
}
}
dataTable2.BeginLoadData();
while (_reader.Read())
{
DataRow dataRow = dataTable2.NewRow();
for (int j = 0; j < arrayList.Length; j++)
{
dataRow[arrayList[j]] = _reader[arrayList[j]];
}
dataTable2.Rows.Add(dataRow);
}
_reader.Close();
dataTable2.EndLoadData();
return dataTable2;
}

Categories

Resources