Cheers,
Im trying to insert a database value to my string array.
for some reason, it says :
"Object reference not set to an instance of an object."
This is my code :
if (IsPostBack)
{
if (RadioWords.Checked == true)
{
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string SqlCount = "SELECT COUNT(*) FROM WordGame";
SqlCommand command = new SqlCommand(SqlCount, con);
//Sets an array of the size of the database.
int count = (Int32)command.ExecuteScalar();
arrOfWords = new string[count];
//Initialize the words in the array.
for (int i = 0; i < arrOfWords.Length; i++)
{
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
string Sqlinsert = "SELECT Word FROM WordGame WHERE ID='"+GetRandomNumber+"'";
SqlCommand commandToRandom = new SqlCommand(Sqlinsert, con);
arrOfWords[i] = commandToRandom.ExecuteScalar().ToString();
}
}
and its refering to this line :
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
Thanks for the helpers!
rnd is null , add a line
rnd = new Random();
at the start of your event
rnd = new Random();
Instantiate rnd as above. You're using a null object that causes the exception in your question to be thrown.
Related
i have to store a select query result in a variable .i'm new in asp.net . i used executescalar but it doesn't work. i try many times but i failed here my last try :
using (SqlConnection sqlConnection = new SqlConnection())
{
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
sqlConnection.ConnectionString = connetionString;
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlConnection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
string result = dataset.Tables[0].ToString();
}
Can you fix the code to me? i have to store the result in a variable
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
string result = null;
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
result = cmd.ExecuteScalar().ToString();
}
Is anyone can tell me, why I'm getting error here.
If pass a value to parameters with this line
int qID = 10087;
It works fine, but when I try this line
int qID = Int32.Parse(corr[0]);
It gives me error (failed), rest of code is same in both situations. What could be a problem here?
int pID1 = 102;
//int qID = 10087;
int qID = Int32.Parse(corr[0]);
using (var cn1 = new SqlConnection(WebConfigurationManager.ConnectionStrings["lConn"].ConnectionString))
{
cn1.Open();
string sql1 = "SELECT DISTINCT Q FROM QATXT WHERE S= #pID AND QID=#qID ";
SqlCommand cmd1 = new SqlCommand(sql1, cn1);
cmd1.Parameters.AddWithValue("#pID", pID1);
cmd1.Parameters.AddWithValue("#qID", qID);
SqlDataReader rdr1 = cmd1.ExecuteReader();
if (rdr1.Read())
{
mainQTxt = (string)rdr1.GetValue(0);
}
cn1.Close(); rdr1.Close(); cmd1.Dispose();
}//- End of cn
rep = mainQTxt ;
Try Changing int qID = Int32.Parse(corr[0]); to int qID = Convert.ToInt32(corr[0]);
asp.net & sql server 2014 : why this error appearMust declare the scalar variable"#ID" I looked on goggle and I think it has something to do with insert parameters for ID. Then again I read there could be a typo error.
As I am not going to insert ID column manually I think this is why I am having problem(s) and I don't know how to solve this problem. i cant find out what is missing or wrong could you help please
string query = "insert into LegRent(ID, Day, Date, Name, Nationality, relegon, NatID, Name2, Nationality2, relegon2, NatID2, Type, Building, Flat, UseFor, Duration, StartFrom, EndIn, RentValue, OnlyAr, YearPercent, InsuranceValue, OnlyArInsur, Addres2, Addres) values (#ID, #Day, #Date, #Name, #Nationality, #relegon, #NatID, #Name2, #Nationality2, #relegon2, #NatID2, #Type, #Building, #Flat, #UseFor, #Duration, #StartFrom, #EndIn, #RentValue, #OnlyAr, #YearPercent, #InsuranceValue, #OnlyArInsur, #Addres2, #Addres)";
try
{
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=Construction;Integrated Security=SSPI;";
using (OleDbConnection conn2 = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn2))
{
cmd.Parameters.AddWithValue("#ID", idtxt.Text);
cmd.Parameters.AddWithValue("#Day", daytxt.Text);
cmd.Parameters.AddWithValue("#Date", datetxt.Text);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
cmd.Parameters.AddWithValue("#Nationality", ddNati.Text);
cmd.Parameters.AddWithValue("#relegon", ddRelgon.Text);
cmd.Parameters.AddWithValue("#NatID", NatIDtxt.Text);
cmd.Parameters.AddWithValue("#Name2", namedd2.Text);
cmd.Parameters.AddWithValue("#Nationality2", ddNati2.Text);
cmd.Parameters.AddWithValue("#relegon2", ddRelgon2.Text);
cmd.Parameters.AddWithValue("#NatID2", NatIDtxt2.Text);
cmd.Parameters.AddWithValue("#Type", typrdd.Text);
cmd.Parameters.AddWithValue("#Building", buileddd.Text);
cmd.Parameters.AddWithValue("#Flat", flatdd.Text);
cmd.Parameters.AddWithValue("#UseFor", usetxt.Text);
cmd.Parameters.AddWithValue("#Duration", durationtxt.Text);
cmd.Parameters.AddWithValue("#StartFrom", starttxt.Text);
cmd.Parameters.AddWithValue("#EndIn", endtxt.Text);
cmd.Parameters.AddWithValue("#RentValue", vluetxt.Text);
cmd.Parameters.AddWithValue("#OnlyAr", onlytxt.Text);
cmd.Parameters.AddWithValue("#InsuranceValue", insurtxt.Text);
cmd.Parameters.AddWithValue("#OnlyArInsur", insuronlytxt.Text);
cmd.Parameters.AddWithValue("#YearPercent", percenttxt.Text);
cmd.Parameters.AddWithValue("#Addres2", adresstxt2.Text);
cmd.Parameters.AddWithValue("#Addres", adresstxt.Text);
conn2.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
lbl_msg.Text = "تـــم الحفظ";
int rentMonths = 0;
bool isInt = int.TryParse(durationtxt.Text, out rentMonths);
if (isInt)
{
for (int index = 0; index < rentMonths; index++)
{
OleDbCommand insertRentMonths = new OleDbCommand("INSERT INTO [dbo].[AccRentReceipt] ([ReceiptID] ,[ContractID] ,[Name]) VALUES (#ReceiptID ,#ContractID ,#Name)", conn2);
cmd.Parameters.AddWithValue("#ReceiptID", index + 1);
cmd.Parameters.AddWithValue("#ContractID", ID);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
}
}
}
}
}
catch (Exception ex)
{
lbl_msg.Text = "خطــــأ " + ex.Message;
}
I have problem with ASP.net and stored procedure
My procedure in SQL Server:
ALTER PROCEDURE [dbo].[top1000]
#Published datetime output,
#Title nvarchar(100) output,
#Url nvarchar(1000) output,
#Count INT output
AS
SET #Published = (SELECT TOP 1000 dbo.vst_download_files.dfl_date_public FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC )
SET #Title = (SELECT TOP 1000 dbo.vst_download_files.dfl_name FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Url = (SELECT TOP 1000 dbo.vst_download_files.dfl_source_url FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Count = (SELECT TOP 1000 dbo.vst_download_files.dfl_download_count FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
And my procedure in website project
public static void Top1000()
{
List<DownloadFile> List = new List<DownloadFile>();
SqlDataReader dbReader;
SqlParameter published = new SqlParameter("#Published", SqlDbType.DateTime2);
published.Direction = ParameterDirection.Output;
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Direction = ParameterDirection.Output;
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Direction = ParameterDirection.Output;
SqlParameter count = new SqlParameter("#Count", SqlDbType.Int);
count.Direction = ParameterDirection.Output;
SqlParameter[] parm = {published, title, count};
dbReader = MsSqlProvider.ExecProcedure("top1000", parm);
try
{
while (dbReader.Read())
{
DownloadFile df = new DownloadFile();
//df.AddDate = dbReader["dfl_date_public"];
df.Name = dbReader["dlf_name"].ToString();
df.SourceUrl = dbReader["dlf_source_url"].ToString();
df.DownloadCount = Convert.ToInt32(dbReader["dlf_download_count"]);
List.Add(df);
}
XmlDocument top1000Xml = new XmlDocument();
XmlNode XMLNode = top1000Xml.CreateElement("products");
foreach (DownloadFile df in List)
{
XmlNode productNode = top1000Xml.CreateElement("product");
XmlNode publishedNode = top1000Xml.CreateElement("published");
publishedNode.InnerText = "data dodania";
XMLNode.AppendChild(publishedNode);
XmlNode titleNode = top1000Xml.CreateElement("title");
titleNode.InnerText = df.Name;
XMLNode.AppendChild(titleNode);
}
top1000Xml.AppendChild(XMLNode);
top1000Xml.Save("\\pages\\test.xml");
}
catch
{
}
finally
{
dbReader.Close();
}
}
And if I made to MsSqlProvider.ExecProcedure("top1000", parm); I got
String[1]: property Size has invalid size of 0.
Where I should look for solution? Procedure or method?
You need to specify the length property for url and Title
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Size=1000
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Size=1000
Instead of using an output parameter you can change your query like the one below
ALTER PRocedure [dbo].[top1000]
As
Begin
Select top 1000 dfl_date_public ,dfl_name,dfl_source_url,
dfl_download_count from dbo.vst_download_files
order by dbo.vst_download_files.dfl_download_count DESC
Then use execute reader
SqlCommand command =
new SqlCommand("top1000", connection);
command.CommandType=CommandType.StoredProcedure
SqlDataReader reader = command.ExecuteReader();
// Iterate through reader as u did and add it to the collection
use xelement to frame the XML
foreach (DownloadFile df in List)
{
XElement products=
new XElement("Products",
new XElement("product",
new XElement("published", "data dodania"),
new XElement("title", df.Name)
);
}
I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False