Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
This is my code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.Common;
public class General_function
{
internal System.Windows.Forms.DataGridView DG_ItemShow;
public static object Get_Single_Value(string SQLQuery)
{
try
{
object SingleValue = null;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = SQLQuery;
SingleValue = cmd.ExecuteScalar;
return SingleValue;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Get_Single_Value : " + ex.Message);
}
}
public static long get_Max_value(string tablename, string fieldname)
{
try
{
long maxvalue = 0;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = "select max(" + fieldname + ") From " + tablename;
string res = null;
res = cmd.ExecuteScalar.ToString;
if (string.IsNullOrEmpty(res))
{
maxvalue = 0;
}
else
{
maxvalue = long.Parse(res);
}
return maxvalue;
}
catch (Exception ex)
{
Interaction.MsgBox("Error in get_Max_value" + ex.Message);
}
}
public static int Save_Record(ArrayList Al, string TableName)
{
try
{
int Retval = 0;
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = ds.Tables(TableName);
ArrayList tal = new ArrayList();
foreach (DataColumn cl in dt.Columns)
{
tal.Add(cl.ColumnName);
}
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string n = null;
for (int i = 0; i <= tal.Count - 1; i++)
{
n = "#" + tal(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = n;
pa.Value = Al(i);
cmd1.Parameters.Add(pa);
}
n = "";
string v = "";
string sqlstr = "insert into " + TableName + " (";
for (int i = 0; i <= tal.Count - 1; i++)
{
n = n + "," + tal(i).ToString;
v = v + ",#" + tal(i).ToString;
}
n = Strings.Right(n, Strings.Len(n) - 1);
v = Strings.Right(v, Strings.Len(v) - 1);
sqlstr = sqlstr + n + ") values (" + v + ")";
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Save_Record : " + ex.Message);
}
}
public static int Delete_Record(ArrayList AlName, ArrayList AlValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "delete from " + TableName + " where ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + " And " + AlName(i).ToString + "=#" + AlName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 4);
sqlstr = sqlstr + v;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Delete_Record : " + ex.Message);
}
}
public static int Modify_Record(ArrayList AlName, ArrayList AlValue, ArrayList
AlPKName, ArrayList AlPKValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
//values parameters
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
//primary key column parameters
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
m = "#" + AlPKName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlPKValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "update " + TableName + " set ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + "," + AlName(i).ToString + "=#" + AlName(i).ToString;
}
string w = "";
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
w = w + " And " + AlPKName(i).ToString + "=#" + AlPKName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 1);
w = Strings.Right(w, Strings.Len(w) - 4);
sqlstr = sqlstr + v + " Where " + w;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Modify_Record : " + ex.Message);
}
}
public static DataTable RecordSearch(string SqlString, string TableName)
{
try
{
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = default(DataTable);
DbDataAdapter da = database_Object.GetAdapter(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
cmd.Connection = cnn;
cmd.CommandText = SqlString;
da.SelectCommand = cmd;
da.Fill(ds, TableName);
dt = ds.Tables(TableName);
cnn.Close();
cmd.Dispose();
da.Dispose();
cnn.Dispose();
return dt;
}
catch (Exception ex)
{
Interaction.MsgBox("error in RecordSearch : " + ex.Message);
}
}
}
How can I call the this class method from another page?
Using your static methods, you just call them by referencing the namespace:
object result = General_function.Get_Single_Value("select * from table");
as shown in code, you defined method as static so in order to invoke that method u can use,
var o = General_function.Get_Single_Value("your_parameter");
and
long lobj = General_function.get_Max_value("table_name","field_name");
and so on...
Related
I have 1000 hiddenfield. How can i put their value in sql database using for loop. Like:
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
string sqlquery = ("INSERT INTO [" + table_name2 + "] (CT1) VALUES ('" + p + "')");
SqlCommand command = new SqlCommand(sqlquery, Connection);
command.ExecuteNonQuery();
}
change tablename as requred!
string query = "INSERT INTO tablename ( CT1 ) VALUES ( #value )";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con);
try
{
cmd.Parameters.Add("#value", System.Data.SqlDbType.VarChar);
con.Open();
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
cmd.Parameters["#value"].Value = p;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//Show exception as required!
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
I'm using Transactions on my Dao and in particular I'm using the TransactionScope object for the first time. But when I compile and start my procedure on my pc the method I wrote in will give me this error:
Connection must be valid and open to commit transaction
code:
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (TransactionScope scope = new TransactionScope())
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteReader();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
//cmd.Transaction = Transazione;
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteReader();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}
You need to move scope.Complete(); within your connection using as it is being disposed before you are completing your scope. Also, change your calls to use ExecuteNonQuery as opposed to ExecuteReader, as you are opening a SqlDataReader and not disposing of it.
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
ok Ok i have inverted using connection with scope
And I opened the connection before scope and works !
I hope it is right, thank you !
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
using (TransactionScope scope = new TransactionScope())
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}
i'm building GPS application where GPS devices send location by tcp port
i'm building a service to read these messages and save it to database
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8889);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
// Console.WriteLine(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
// Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
// Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}
//Class to handle each client request separatly
public class handleClinet
{
static void WriteLog(string message, EventLogEntryType type)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry(message, type, 101, 1);
}
}
static int InsideDangerArea(double Lat, double Lng)
{
string point = "POINT(" + Lng + " " + Lat + ")";
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Select id from T_Geofncies", conn))
{
DataTable dt = new DataTable();
dt.Load(comm.ExecuteReader());
foreach (DataRow dr in dt.Rows)
{
string Query = " DECLARE #g geometry; DECLARE #h geometry; SET #g = (select(points) from T_Geofncies where id=" + dr["id"].ToString() + " );";
Query += " SET #h = geometry::STGeomFromText('" + point + "', 4326); SELECT #g.STContains(#h);";
comm.CommandText = Query;
int Val = Convert.ToInt32(comm.ExecuteScalar());
if (Val == 1)
{
conn.Close();
conn.Dispose();
return Convert.ToInt32(dr["id"]);
}
}
}
conn.Close();
conn.Dispose();
}
return 0;
}
static int OutsideSafeArea(double Lat, double Lng)
{
string point = "POINT(" + Lng + " " + Lat + ")";
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Select id from T_SafeArea", conn))
{
DataTable dt = new DataTable();
dt.Load(comm.ExecuteReader());
foreach (DataRow dr in dt.Rows)
{
string Query = " DECLARE #g geometry; DECLARE #h geometry; SET #g = (select(points) from T_SafeArea where id=" + dr["id"].ToString() + " );";
Query += " SET #h = geometry::STGeomFromText('" + point + "', 4326); SELECT #g.STContains(#h);";
comm.CommandText = Query;
int Val = Convert.ToInt32(comm.ExecuteScalar());
if (Val == 1)
{
conn.Close();
conn.Dispose();
return Convert.ToInt32(dr["id"]);
}
}
}
conn.Close();
conn.Dispose();
}
return 0;
}
static SqlGeography GetGeographyFromText(String pText)
{
SqlString ss = new SqlString(pText);
SqlChars sc = new SqlChars(ss);
try
{
return SqlGeography.STPointFromText(sc, 4326);
}
catch (Exception ex)
{
throw ex;
}
}
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
string ConnStr = "Data Source =.; Initial Catalog = GPS_Tracking;Integrated Security = True";
int requestCount = 0;
// byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
int i;
int size = (int)clientSocket.ReceiveBufferSize;
// Loop to receive all the data sent by the client.
Byte[] bytes = new Byte[size];
string data = "";
string IMEI;
while ((i = networkStream.Read(bytes, 0, bytes.Length)) != 0)
{
try
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
string[] tokens = data.Split(new[] { "GPRMC" }, StringSplitOptions.None);
var longest = Regex.Matches(data, #"\d+").Cast<Match>().OrderByDescending(m => m.Length).First();
IMEI = longest.ToString();
if (IMEI.Length > 15)
IMEI = IMEI.Substring(1);
foreach (string item in tokens)
{
try
{
string[] Values = item.Split(','); // Console.WriteLine("Received: {0}", data);
string time = Values[1];
// Console.WriteLine("Time= " + time);
string lat;
string lng;
string speed;
string date;
lat = Values[3];
lng = Values[5];
speed = Values[7];
date = Values[9];
string NewDString = date.Substring(2, 2) + date.Substring(0, 2) + date.Substring(4, 2);
// Console.WriteLine("IMEI= " + IMEI);
// Alternate choice: If the string has been input by an end user, you might
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
string myDate = (NewDString + time).Insert(2, "-").Insert(5, "-").Insert(8, " ").Insert(11, ":").Insert(14, ":");
double latDeg = Convert.ToDouble(Convert.ToDouble(lat).ToString().Substring(0, 2));
double latMin = Convert.ToDouble(Convert.ToDouble(lat).ToString().Substring(2));
double lngDeg = Convert.ToDouble(Convert.ToDouble(lng).ToString().Substring(0, 2));
double lngmin = Convert.ToDouble(Convert.ToDouble(lng).ToString().Substring(2));
double latmap = latDeg + (latMin / 60);
// OldLat=
double lngmap = lngDeg + (lngmin / 60);
//if ((Math.Round(latmap, 3) != Math.Round(OldLat, 3) && Math.Round(lngmap, 3) != Math.Round(OldLng, 3)) || idleRecord > 30)
//{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
// DbCommand also implements IDisposable
// create command with placeholders
cmd.CommandText =
"INSERT INTO T_Tracking " +
"([IMEI], [TrackTime], [Longitude], [Lattitude], [speed],[MapPoint],[SafeAreaID],[GeoFenceID]) " +
"VALUES(#IMEI, #TrackTime, #Longitude, #Lattitude, #speed,#MapPoint,#SafeAreaID,#GeoFenceID)";
SqlParameter p_IMEI = new SqlParameter("#IMEI", IMEI);
cmd.Parameters.Add(p_IMEI);
SqlParameter p_TrackTime = new SqlParameter("#TrackTime", myDate);
cmd.Parameters.Add(p_TrackTime);
SqlParameter p_Longitude = new SqlParameter("#Longitude", lngmap);
cmd.Parameters.Add(p_Longitude);
SqlParameter p_Lattitude = new SqlParameter("#Lattitude", latmap);
cmd.Parameters.Add(p_Lattitude);
SqlParameter p_Speed = new SqlParameter("#speed", speed);
cmd.Parameters.Add(p_Speed);
SqlParameter p_Points = new SqlParameter("#MapPoint", System.Data.SqlDbType.Udt);
p_Points.UdtTypeName = "geometry";
p_Points.Value = GetGeographyFromText("Point(" + lngmap + " " + latmap + ") ");
cmd.Parameters.Add(p_Points);
SqlParameter P_Safe = new SqlParameter("#SafeAreaID", OutsideSafeArea(latmap, lngmap));
cmd.Parameters.Add(P_Safe);
SqlParameter P_GeoFence = new SqlParameter("#GeoFenceID", InsideDangerArea(latmap, lngmap));
cmd.Parameters.Add(P_GeoFence);
// execute
cmd.ExecuteNonQuery();
}
//}
//else
// idleRecord = idleRecord + 1;
}
}
catch (Exception exp) { WriteLog(exp.ToString(), EventLogEntryType.Error); }
}
}
catch { }
}
}
catch (Exception ex)
{
// Console.WriteLine(" >> " + ex.ToString());
}
}
}
}
}
it is working fine but the problem is performance
it is test system with 5 devices
it consume 95% memory on server on 10 minutes
what can be done to optimize that code
Thank You
The problem here is that every time a new socket connection comes in you are creating a new thread that never ends even when the underlying connection is closed. The thread procedure is wrapped with a catch-all exception handler inside a while (true) loop, and so when the socket connection is closed and a SocketException thrown this is caught and ignored and the thread procedure loops again. This will also prevent garbage collection of the socket objects and is probably highly CPU intensive as well. Also the cleanup code at the end of main will never be called because of the while(true) there, and indeed would only close the last client connection.
Your thread procedure should correctly handle exceptions and stop looping when the underlying socket connection is closed.
i have a problem in fetching value from data gridview. In the same event i am able to fetch value from datagrid view1 but in same event i am not able to fetch the value from datagridview2. Help me with correction in following code.
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(path);
SqlConnection con1 = new SqlConnection(path);
con.Open();
string selectSql = "select * from textbooks where class='" + txt_class.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(selectSql, con);
string textname = "";
tempcnt.Text = "test";
string bookname = "";
double bookquantity = 0;
string textname1 = "";
string bookname1 = "";
double stockquantity1 = 0;
double bookquantity1 = 0;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
bookname = (reader["name"].ToString());
bookquantity = Convert.ToInt32(reader["quantity"]);
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
textname = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
if (textname == bookname)
{
bookquantity = bookquantity - 1;
temp_count.Text = bookquantity.ToString();
con1.Open();
string uquery = "update textbooks set quantity=" + bookquantity + " where name='" + bookname + "'";
SqlCommand cmd1 = new SqlCommand(uquery, con1);
cmd1.ExecuteNonQuery();
con1.Close();
}
}
}
}
con.Close();
con.Open();
string selectSql2 = "select * from notebooks";
SqlCommand cmd2 = new SqlCommand(selectSql2, con);
tempcnt.Text = "test";
using (SqlDataReader reader1 = cmd2.ExecuteReader())
{
while (reader1.Read())
{
bookname1 = (reader1["name"].ToString());
stockquantity1 = Convert.ToInt32(reader1["quantity"]);
tempcnt.Text = bookname1;
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
textname1 = dataGridView2.Rows[i].Cells[0].Value as string;
string temp = Convert.ToString(dataGridView2.Rows[i].Cells[0].Value);
tempcnt.Text = temp;
if (temp == bookname1)
{
tempcnt.Text = "success";
}
}
}
}
con.Close();
}
Here i need to access the variable delval outside the for loop as in the code below
cmd_mail.Parameters.Add("#deleteusers", SqlDbType.NVarChar).Value = delval;
..How to do this..
Here is my code
for (int i = 0; i <= NoOfUsers - 1; i++) {
using (SqlConnection Conn = new SqlConnection(constr_str)) {
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = Conn;
Conn.Open();
cmd.CommandText = "Select top 1 Login_User_Name from Rode_Provisioning_User where RequestId=#RequestId and CustomerCode =#CustomerCode and disableflag=0 order by User_Count";
cmd.Parameters.Add("#CustomerCode", SqlDbType.VarChar).Value = CustomerCode;
cmd.Parameters.Add("#RequestId", SqlDbType.VarChar).Value = RequestId;
string Loginusername = cmd.ExecuteScalar();
Conn.Close();
string delval = "";
if (string.IsNullOrEmpty(delval)) {
delval = Loginusername;
} else {
delval = delval + "," + Loginusername;
}
}
}
}
if (flag == "Yes") {
string constr_dep = "server=" + _strServer + ";database=" + _strDatabase + ";uid=" + _strUserid + ";pwd=" + _strPassword + ";";
SqlConnection con_dep = new SqlConnection();
con_dep.ConnectionString = constr_dep;
SqlCommand cmd_mail = new SqlCommand("delete_user_mailsend_sp", con_dep);
cmd_mail.CommandType = CommandType.StoredProcedure;
cmd_mail.CommandTimeout = 0;
cmd_mail.Parameters.Add("#companycode", SqlDbType.NVarChar).Value = CustomerCode
cmd_mail.Parameters.Add("#deleteusers", SqlDbType.NVarChar).Value = delval;
try {
con_dep.Open();
cmd_mail.ExecuteNonQuery();
} catch (SqlException ee) {
VWLogger.LogMessage("Exception in delete_user_mailsend_sp:", TraceEventType.Critical);
VWLogger.LogMessage(ee, TraceEventType.Critical);
return ee.Message;
flag = ee.Errors(0).ToString();
}
con_dep.Close();
}
Any suggestion?
Define it outside the loop then, and it will be visible in both blocks, as well as outside.
As zerkms said, declare it outside the loop. See below.
string delval = "";
for (int i = 0; i <= NoOfUsers - 1; i++)
{
// your existing stuff
// ...
if (string.IsNullOrEmpty(delval))
{
delval = Loginusername;
}
else
{
delval = delval + "," + Loginusername;
}
}
if (flag == "Yes")
{
// your existing stuff
// ...
cmd_mail.Parameters.Add("#deleteusers", SqlDbType.NVarChar).Value = delval;
}