how can i convert DataFrame into DataSet in VB.NET? - vb.net

i am using R.Net. in that i have done some database connection using R.Net in that i am getting the result in DataFrame format i need to convert it into DataSet
here is my code:
REngine.SetDllDirectory("#C:\Program Files\R\R-2.12.0\bin\i386")
engine = REngine.CreateInstance("RDotNet")
engine.EagerEvaluate("library(RODBC);")
engine.EagerEvaluate("con <- odbcConnect(dsn='rdsn', uid = 'sa', pwd = 'surya');")
cmdStr = SELECT DISTINCT Investment.InvestmentTypeCode,InvestmentTypeDescription, SortID FROM Investment,InvestmentTypeDef WHERE(Investment.InvestmentTypeCode = InvestmentTypeDef.InvestmentTypeCode) ORDER BY SortID
engine.EagerEvaluate("frm <- sqlQuery(con, '" + cmdStr + "');")
engine.GetSymbol("frm").AsDataFrame()
if any one knows plz help me...

There is not built-in functionality in R.Net or in the .NET Framework which can do that. But you can create and fill DataSets programmatically. So you will have to write your own conversion code.
See:
Creating A DataSet Programmatically

I recently had to convert a RDataFrame to a standard DataTable in C# - I'm assuming all the columns contain doubles:
public static DataTable RDataFrameToDataSet(DataFrame resultsMatrix) {
var dt = new DataTable();
var columns = new DataColumn[resultsMatrix.ColumnCount];
for (int i = 0; i < resultsMatrix.ColumnCount; i++) {
columns[i] = new DataColumn(resultsMatrix.ColumnNames[i], typeof(double));
}
dt.Columns.AddRange(columns);
for (int y = 0; y < resultsMatrix.RowCount; y++) {
var dr = dt.NewRow();
for (int x = 0; x < resultsMatrix.ColumnCount; x++) {
try {
dr[x] = resultsMatrix[y, x];
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
dt.Rows.Add(dr);
}
return dt;
}

Related

RDLC Design, A column of Row number showing extra value

My rdlc report is working fine. but displaying 0 that i need to remove. please help. attached screenshot describe the design problem.enter image description here
C# code
protected void GenerateReport()
{
if (Request.QueryString["rdlcrepname"] != null)
{
reportName = Request.QueryString["rdlcrepname"].ToString();
string strprm1 = Request.QueryString["prm1"].ToString();
var strprm2 = Request.QueryString["param2"] != null ? Convert.ToInt32(Request.QueryString["param1"].ToString()) : 0 ;
SqlParameter[] clsParam = new SqlParameter[2];
clsParam[0] = new SqlParameter("#param1", strprm1);
clsParam[1] = new SqlParameter("#param2", strprm2);
ds = dataAccess.GetDataSet("spname", clsParam);
dsShow.Tables.Add();
dsShow.Tables.Add("FinalDisplayDataHeader");
dsShow.Tables.Add("FinalDisplayData");
//DataColumns-Header SQL of Header
dsShow.Tables["FinalDisplayDataHeader"].Columns.Add("col1", typeof(string));
dsShow.Tables["FinalDisplayDataHeader"].Columns.Add("col2", typeof(string));
dsShow.Tables["FinalDisplayDataHeader"].Columns.Add("col3", typeof(string));
dsShow.Tables["FinalDisplayDataHeader"].Columns.Add("col4", typeof(string));
//DataColumns SQL of data
dsShow.Tables["FinalDisplayData"].Columns.Add("col1", typeof(string));
dsShow.Tables["FinalDisplayData"].Columns.Add("col2", typeof(string));
dsShow.Tables["FinalDisplayData"].Columns.Add("col3", typeof(string));
if (ds.Tables["Table"].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables["Table"].Rows.Count; i++)
{
dsQPUDisplay.Tables["FinalDisplayDataHeader"].Rows.Add(); //Header
dsShow.Tables["FinalDisplayDataHeader"].Rows[i]["col1"] = ds.Tables["Table"].Rows[i]["col1"].ToString();
dsShow.Tables["FinalDisplayDataHeader"].Rows[i]["col2"] = ds.Tables["Table"].Rows[i]["col2"].ToString();
dsShow.Tables["FinalDisplayDataHeader"].Rows[i]["col3"] = ds.Tables["Table"].Rows[i]["col3"].ToString();
dsQPUDisplay.Tables["FinalDisplayDataHeader"].Rows[i]["col4"] = ds.Tables["Table"].Rows[i]["col4"].ToString();
for (int k = 0; k < 4; k++)
{
dsShow.Tables["FinalDisplayData"].Rows.Add(); //Data
dsShow.Tables["FinalDisplayData"].Rows[k]["col1"] = ds.Tables["Table1"].Rows[k]["col1"].ToString();
dsShow.Tables["FinalDisplayData"].Rows[k]["col2"] = ds.Tables["Table1"].Rows[k]["col2"].ToString();//This is right
dsShow.Tables["FinalDisplayData"].Rows[k]["col3"] = ds.Tables["Table1"].Rows[k]["col3"].ToString();
}
}
reportPath = string.Empty;
rdlcReportViewer.LocalReport.ReportPath = GetReportPath(reportName);
//rdlcReportViewer.LocalReport.DataSources.Clear();
ReportDataSource rdsHeader = new ReportDataSource("DataHeader", dsShow.Tables["FinalDisplayDataHeader"]);
ReportDataSource rdsData = new ReportDataSource("Data", dsShow.Tables["FinalDisplayData"]);
rdlcReportViewer.LocalReport.DataSources.Add(rdsQPUheader);
rdlcReportViewer.LocalReport.DataSources.Add(rdsQPUData);
}// for complete batch students loop closed
rdlcReportViewer.DataBind();
rdlcReportViewer.LocalReport.Refresh();
}
}
RDLC is in design. code above give you idea how i am generating the rdlc report. enter image description here this link describe issue of RowNumber display
My issue got resolved by enabling regional formatting option of the particular textbox. Click on the link to view image

Get Data from GridView to RdotNet (R.net)

my task is simple i just wanna take data from gridview to REngine do random function get back rows and show them back in the gridview, I tried that
TextBox_Ville.Text = "I'm here";
DataTable dtb = (DataTable)Session["Grid"];
REngine engine = REngine.GetInstance();
string[,] stringData = new string[dtb.Rows.Count, dtb.Columns.Count];
for (int row = 0; row < dtb.Rows.Count; row++)
{
for (int col = 0; col < dtb.Columns.Count; col++)
{
stringData[row, col] = dtb.Rows[row].ItemArray[col].ToString();
}
}
CharacterMatrix matrix = engine.CreateCharacterMatrix(stringData);
engine.SetSymbol("myRDataFrame", matrix);
engine.Evaluate("myRDataFrame <- as.data.frame(myRDataFrame, stringsAsFactors = FALSE)");
// engine.Evaluate("str(myRDataFrame)");
DataFrame dataset = engine.Evaluate("myRDataFrame[sample(nrow(myRDataFrame), 1), ]").AsDataFrame();
DataTable dtt = new DataTable();
for (int i = 0; i < dataset.ColumnCount; ++i)
{
dtt.Columns.Add(new DataColumn(dataset.ColumnNames[i]));
}
for (int i = 0; i < dataset.RowCount; ++i)
{
var row = dtt.NewRow();
for (int k = 0; k < dataset.ColumnCount; ++k)
{
row[dataset.ColumnNames[k]] = dataset[i, k];
}
dtt.Rows.Add(row);
}
GridView1.DataSource = dtt;
GridView1.DataBind();
But it give me Stackoverflow error, can anyone help please. thanks :)
I see you omitted type when building your DataTable. Perhaps that is the problem?
dtt.Columns.Add(new DataColumn(dataset.ColumnNames[i], typeof(string)));
The other thing I noticed is that you use 'row' as an iterator in a for loop, then you use it again to build a DataRow. I can't tell if it's a problem or not.

Using C# remove unnecessary “TABLE_NAME” from Excel worksheets

Can anyone tell me, I am going to upload excel file, this file has unnecessary table like "_xlnm#Print_Titles" that I need to remove or delete that field. This a my method. But it is does not work for remove or delete.
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if ((dt == null) )
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
if ((excelSheetNames[i].Contains("_xlnm#Print_Titles") || (excelSheetNames[i].Contains("Print_Titles"))))
{
if (true)
{
row.Table.Rows.Remove(row);
dt.AcceptChanges();
}
}
i++;
}
return excelSheetNames;
}
Instead of removing items in the foreach loop, we'll find them and add them to a list, then we'll go through that list and remove them from your data table.
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if ((dt == null))
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
var rowsToRemove = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
var row = dt.Rows[i];
excelSheetNames[i] = row["TABLE_NAME"].ToString();
if ((excelSheetNames[i].Contains("_xlnm#Print_Titles") || (excelSheetNames[i].Contains("Print_Titles"))))
{
rowsToRemove.Add(dt.Rows[i]);
}
i++;
}
foreach (var dataRow in rowsToRemove)
{
dt.Rows.Remove(dataRow);
}
return excelSheetNames;
}
Those _xlnm and "$" are sheets that, turns out, shouldn't be normally accessed by the users.
You can solve this in 2 ways.
Ignore them
Drop them
The former is highly recommended.
To do this you need to use the following code:
if (!dt.Rows[i]["Table_Name"].ToString().Contains("FilterDatabase") && !dt.Rows[i]["Table_Name"].ToString().EndsWith("$'"))
{
}
You can either use .Contains() and/or .EndsWith() to filter out those sheets.

retrieve lisbox value in database using C#

actually iam using one listbox which have multiple values when user select a values the item in listbox are inserted database like "Abc,xyz,gkl" type now i want to retrieve this value from database in front of form and as Selected how can i do that here is the my code
ds = new DataSet();
if (ds.Tables[0].Rows.Count > 0)
{
string[] arr_Electro_Therapy = ds.Tables[0].Rows[0]["Electro_Therapy"].ToString().Trim().Split(',');
for (int i = 0; i < arr_Electro_Therapy.Length; i++)
{
for (int k = 0; k < listBox1.Items.Count; k++)
{
if (listBox1.Items[k].Value.ToString().Trim() == arr_Electro_Therapy[i].ToString().Trim())
{
listBox1.Items[k].Selected = true;
hdSelected.Value = hdSelected.Value + ", " + listBox1.Items[k].;
}
}
}

Topic views do not show up in jTable

I try to code a forum using java swing. Firstly, on click for the jTable, it will lead to eForumContent.class which pass in the id together.
jTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
int id = 0;
eForumTopics topics = new eForumTopics(id);
topics.retrieveDiscussion();
eForumThreadContent myWindow = new eForumThreadContent(id);
myWindow.getJFrame().setVisible(true);
}
});
I initialize the id first. But I set my id in database table to auto number. Then I call the retrieveDiscussion method to get the id from database and pass it to eForumThreadContent. Here are my codes for retrieveDiscussion method.
public boolean retrieveDiscussion(){
boolean success = false;
ResultSet rs = null;
DBController db = new DBController();
db.setUp("IT Innovation Project");
String dbQuery = "SELECT * FROM forumTopics WHERE topic_id = '" + id
+ "'";
rs = db.readRequest(dbQuery);
db.terminate();
return success;
}
}
Then, inside the eForumThreadContent, I want to display the content of chosen thread using a table. So I use the id which I pass in just now and insert into my sql statement. Here are my codes.
public eForumThreadContent(int id) {
this.id = id;
}
if (jTable == null) {
Vector columnNames = new Vector(); // Vector class allows dynamic
// array of objects
Vector data = new Vector();
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select topic_title,topic_description,topic_by from forumTopics WHERE topic_id = '"+id+"'";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(400); // second column is bigger
}else {
column.setPreferredWidth(200);
}
}
String header[] = { "Title", "Description", "Posted by" };
for (int i = 0; i < jTable.getColumnCount(); i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel()
.getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.getTableHeader().setFont( new Font( "Dialog" , Font.PLAIN, 20 ));
jTable.getTableHeader().setForeground(Color.white);
jTable.getTableHeader().setBackground(new Color(102, 102, 102));
jTable.setEnabled(false);
jTable.setRowHeight(100);
jTable.getRowHeight();
jTable.setFont( new Font( "Dialog" , Font.PLAIN, 18 ));
}
return jTable;
}
However, the table inside eForumThreadContent is empty even when I clicked on certain thread. It also gives me an error message.
[Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at DBController.database.DBController.readRequest(DBController.java:27)
at kioskeForum.entity.eForumTopics.retrieveDiscussion(eForumTopics.java:67)
at kioskeForum.ui.eForumDiscussion$3.mouseClicked(eForumDiscussion.java:296)
I research online to get an idea for topic views using id. But my table does not show up anything. Can somebody enlighten me how to fix it? Or any other ways to display topic views in java swing? Thanks in advance.