using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
public class StockMainDL
{
string conString = "Data Source=KamranAhmed\\SQLEXPRESS;Initial Catalog=City_Car;Integrated Security=True";
SqlConnection con;
SqlCommand com;
SqlDataAdapter da;
DataSet ds;
public StockMainDL()
{
con = new SqlConnection(conString);
con.Open();
}
public List<StockMain> GetChartData(string mode)
{
List<StockMain> stockMain = new List<StockMain>();
string query = "SELECT * FROM StockMain";
com = new SqlCommand(query);
da = new SqlDataAdapter(query, con);
da.Fill(ds);
foreach (DataRow item in ds.Tables[0].Rows)
{
stockMain.Add(new StockMain(Int32.Parse(item["Stid"]), Int32.Parse(item["Vrno"]), Int32.Parse(item["Vrnoa"]), Convert.ToDateTime(item["Vrdate"]), item["Party_id"].ToString(), item["Bilty_No"].ToString(), Convert.ToDateTime(item["Bilty_Date"]), item["Received_By"].ToString(), item["Transporter_id"].ToString(), item["Remarks"].ToString(), Int32.Parse(item["Year_Srno"]), item["EType"].ToString(), Int32.Parse(item["NAmount"]), Int32.Parse(item["UId"]), Int32.Parse(item["VrNo"]), Int32.Parse(item["OrderVrNo"]), Int32.Parse(item["Freight"]), item["Party_Id_Co"].ToString(), Int32.Parse(item["SaleBillNo"]), float Discp, float Discount, Int32.Parse(item["Currency_Id"]), float Expense, Int32.Parse(item["Company_Id"]), item["Vehicle_Id"].ToString(), Convert.ToBoolean(Item["IsEditted"]), Convert.ToBoolean(Item["IsNew"]), Convert.ToBoolean(Item["IsDeleted"])));
}
return stockMain;
}
}
Above is the code that I'm using to first get the dataset from the database and the transform this dataset to a List and then return this list. The problem I'm having is, inside the foreach loop it gives this error "Cannot use 'Int32' before it is declared", I tried to use Convert.ToInt32() it gives the same error for "Convert".
Can anybody please tell me what I'm doing wrong?
Thanks
you are using Item instead of item inside that FOR loop for few parameters. That is throwing you this error. Remember the variables used are case-sensitive
Related
Ths code as it appears works fine but here i insert by Add. all the values into the listTables. While what I want is to assing an object variable (User::Hosps) from SSIS (system.object) to the list (or to an array)
How can it be done?
This part:
OleDbDataAdapter A = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
A.Fill(dt, Dts.Variables["User::Hosps"].Value);
is something i found online and tryed to use but the values it assigns to the list are not the values i want from the object.
#region Namespaces
using System;
using System.Data;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.OleDb;
using Microsoft.SqlServer.Dts.Runtime;
using System.Diagnostics;
using System.Collections.Generic;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
#endregion
namespace ST_ef6fc7b20ff94cbfb2587ed23a6520a0
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
OleDbDataAdapter A = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
A.Fill(dt, Dts.Variables["User::Hosps"].Value);
foreach (DataRow row in dt.Rows)
{
Tables.Add(row.ToString());
}
List<string> Tables = new List<string>();
Tables.Add("ABRAVIV");
Tables.Add("FLIMANAVIV");
Tables.Add("BSHAVIV");
Tables.Add("LEVAVIV");
Tables.Add("BEERAVIV");
Tables.Add("TIRAAVIV");
Tables.Add("SHRAVIV");
Tables.Add("MAZAVIV");
Tables.Add("NTNYAAVIV");
Tables.Add("SHMUELAVIV");
Tables.Add("PARDESAVIV");
Tables.Add("RISHONAVIV");
Parallel.ForEach(Tables, Table =>
{
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "Data Source=vmbi-devdb\\gp;Initial Catalog=GP;Integrated Security=True;Pooling=false;";
SqlDataReader rdr = null;
myConnection.Open();
SqlCommand cmd = new SqlCommand("exec Mirror_Logistic.Load_Table_From_Source " + Table, myConnection);
cmd.CommandTimeout = 0;
rdr = cmd.ExecuteReader();
myConnection.Close();
});
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Actually the variable User::Hosps contains the same values i assigned with the Tables.Add
Sorry, you got me confused.
Do you want to assign the values from ur SSIS-Object to a list?
Or do you want to assign ur values from C# to your object?
public void Main()
{
OleDbDataAdapter A = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
A.Fill(dt, Dts.Variables["User::Hosps"].Value); List<string> myValues = new list<string>();
foreach (DataRow row in dt.Rows)
{
myValues.Add(row[0].ToString());
}
I'm trying below code in c# windows application that's working fine to retrieve a single image from a SQL Server database table.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace ManagementSystem
{
public partial class frmSearchResult : Form
{
public frmSearchResult()
{
InitializeComponent();
}
SqlConnection con;
SqlCommand cmd;
private void cmdSearch_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=managementsystem;Integrated Security=True");
con.Open();
cmd = new SqlCommand("Select M_Photo, S_Photo From Members where M_Number=15", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["M_Photo"]);
pic_M.Image = new Bitmap(ms);
}
}
}
}
but I need to retrieve multiple images from database. When I append below code at the end, I get an error:
Parameter is not valid.
Appended code is
MemoryStream ms1 = new MemoryStream((byte[])ds.Tables[0].Rows[0]["S_Photo"]);
pic_S.Image = new Bitmap(ms1);
What is wrong with this? Please help.
Thanks!
The main problem was with the saving images in the right way. Use below code for each image to save images in the database image fields and use above questioned code to retrieve images.
//Convert image to binary
string imgpathC2 = txtH_C2.Text;
FileStream fsC2;
fsC2 = new FileStream(#imgpathC2, FileMode.Open, FileAccess.Read);
byte[] picbyteC2 = new byte[fsC2.Length];
fsC2.Read(picbyteC2, 0, System.Convert.ToInt32(fsC2.Length));
fsC2.Close();
//Add binary value to SQL parameter
SqlParameter picparaC2 = new SqlParameter();
picparaC2.SqlDbType = SqlDbType.Image;
picparaC2.ParameterName = "picC2";
picparaC2.Value = picbyteC2;
//use parameter in command
cmd.Parameters.Add(picparaC2);
Thanks!
I am trying to create a web application that will use a DropDownList to have a user choose a certain value and a DataList to show certain data. For instance, if the user selects a value from the DropDownList, only data related to the user selected value should be shown in the DataList. I am very new to ASP.NET and to C#.
The code below is what I have implemented in my code behind file. Currently I am getting an ArgumentException error I am not sure how to resolve this issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class Products : System.Web.UI.Page
{
SqlDataAdapter adapter;
DataSet dset;
string connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|#Registration.mdf;Integrated Security=True";
string sql = "select * from Products";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
adapter = new SqlDataAdapter(sql, connstring); //<--ArgumentException error occurs here
dset = new DataSet();
adapter.Fill(dset);
DropDownList1.DataSource = dset.Tables[0];
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "ProductID";
DropDownList1.DataBind();
DataListBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataListBind();
}
public void DataListBind()
{
adapter = new SqlDataAdapter("select * from Products where ProductID=" + DropDownList1.SelectedValue + "", connstring);
dset = new DataSet();
adapter.Fill(dset);
dlProducts.DataSource = dset.Tables[0];
dlProducts.DataBind();
}
}
The problem is you connection string. If you look at the inner exception that you get it says:
Invalid value for key 'attachdbfilename'
This post is further help on this matter.
To get rid of the exception just add a # in front of the string:
string connstring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|#Registration.mdf;Integrated Security=True";
You have'nt created a connection object. I think you need to create and open the connection first.
I recently viewed a youtube tutorial on how to use a c#-class to run sql-commands and fetch data. This is the tutorial I have followed: https://www.youtube.com/watch?v=WG3Hwk7Yp48#t=13m42s at 13:42 you can see that he runs his code, inserts name-values into a textbox and is then able to show the new values in the combobox.
However, whenever I run my code I get this error (fullsize image available here):
The table I am trying to collect/insert data from has a 'unr' int which cannot be null, and a name which is a varchar.
This is my SQL-DAL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace WindowsFormsApplication3
{
class DAL
{
private SqlConnection con;
public SqlCommand cmd;
private SqlDataAdapter da;
private DataTable dt;
public DAL()
{
con = new SqlConnection(#"Data Source=VIKTOR-PC;Initial Catalog=HT2015;Integrated Security=True");
con.Open();
}
public void SqlQuery(string queryText)
{
cmd = new SqlCommand(queryText, con);
}
public DataTable QueryEx()
{
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
return dt;
}
public void NoQueryEx()
{
cmd.ExecuteNonQuery();
}
}
and this is my form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private WindowsFormsApplication3.DAL con;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con = new DAL();
con.SqlQuery("INSERT INTO dbo.Users(name) VALUES (#NameP)");
con.cmd.Parameters.Add("#NameP", textBox1.Text);
con.NoQueryEx();
con.SqlQuery("SELECT name FROM Users");
comboBox1.Items.Clear();
foreach(DataRow dr in con.QueryEx().Rows)
{
comboBox1.Items.Add(dr[1].ToString());
}
}
}
}
Now it keeps saying that unr is null, and all I want is to add new names to the table. I havent got a clue on how to solve this.
Your table Users has not-nullable column unr.
But this query you're using:
INSERT INTO dbo.Users(name) VALUES (#NameP)
doesn't inserts anything into unr - this is the reason you're getting that exception.
You should either insert something into unr in your query or make it nullable (or having some default value) at table definition.
My following code has two problems.
1- It doesn't go to the next row in dataset (when I run it, it just run firefox for 2916 times). I change this it from
var test = url.Replace("<userid>", Convert.ToString(row[userID]));
to
var test = url.Replace("<userid>", Convert.ToString(row["userID"]));
but it shows an error (Column 'userid' does not belong to table).
2- I want to close the firefox webpage page at the end of each loop and for next loop it runs again(because of performance issue)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the userID
adapter.Fill(dt);
int userid=0,trackid=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row[userid]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/userid?groups=userid");
if (client.ToLower() == (Convert.ToString(trackid).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average = " + counter);
}
conn.Close();
}
}
}
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["userid"])); // You need ""
System.Diagnostics.Process.Start(test); // You should use variable test, which contains your url with <userid> replaced.