circular reference in self-nested table 'firstname1'. asp.net - asp.net

This is the error i am getting "circular reference in self-nested table 'firstname1'".
I want to Hierarchical Data binding. Employee and their supervisor are in the same table.
I am taking reference from http://weblogs.asp.net/alessandro/archive/2008/03/01/part-2-building-and-binding-hierarchical-data-from-the-database-to-the-asp-net-navigation-controls.aspx.
But it is giving error on generating Xml.
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["RMSConnection"].ToString()))
{
string SqlCommand = "SELECT EmployeeId,FirstName,ReportToId FROM tblEmployee";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
SqlCommand, con);
adapter.Fill(ds);
ds.Tables[0].TableName = "FirstName1";
DataRelation dr = new DataRelation("pageId_parentId",ds.Tables["FirstName1"].Columns["EmployeeId"], ds.Tables["FirstName1"].Columns["ReportToId"]);
dr.Nested = true;
ds.Relations.Add(dr);
}
//string s= ds.GetXml();
above is my code.
Please Suggest.

You got an infinite loop in your table's data.
You are trying to make a link between EmployeeId and ReportToId but something is wrong.
Your problem is with all your row where the EmployeeId is equal to ReportToId
Exemple:
EmployeeId First Name ReportToId
1 Super 1
In all those cases, you need to set the ReportToId to Null
EmployeeId First Name ReportToId
1 Super Null

Related

Query SQL Server using session variable

I'm trying to query a SQL Server database table based on a user variable (using ASP.NET and C#). I want to be able to pull just the user's unique records from the Waste Application Information table where the Farm Owner name is equal to the variable name (which is a string).
Here's part of my code:
conn.Open();
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = (user variable) ";
SqlCommand com = new SqlCommand(WasteAppData, conn);
GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();
If I replace the "(user variable)" with the actual value in the table column it does work correctly. Like this: 'Joe Smith' I've tried referencing the variable which is pulled from another webform with no luck... I think my syntax is incorrect? Any help would be great!
You need to do it this way:
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = #FarmOwn";
using (SqlCommand cmdSQL = new SqlCommand(WasteAppData , conn)
{
cmdSQL.Parameters.Add("#FarmOwn", SqlDbType.NVarChar).Value = strFarmOwnwer;
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader;
GridView1.DataBind();
}
In this case "strFarmOwner" would be replaced with your actual variable that holds the value you want.

How can I select a single column from a table in SQL Server & put that value into a variable?

I have a table Registration with many columns. I need to get customer_id and put that value into a variable for use that in a session for moving & use between ASP Webforms. How can I do this?
You can use ExecuteScalar method to get single column value. Below is a very basic example of how to get single column value.
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("select Customer_id from Registration", con);
con.Open();
string id = cmd.ExecuteScalar().ToString();
}
Here is how you can store the value in session
Session["CustomerID"] = id;
And here is how you can retrieve the value on second page
int ID = 0;
int.TryParse((string)Session["CustomerID"], out ID);

Saving the result of Select statement from SqlDataReader to list at once

As the questions says, I'm trying to save the result of a select statement from a SqlDataReader to a list at once, rather than one by one giving the column name.
Before that I've tried using reader.read() and then giving the column name one by one and saving the data something like this,
while (reader.Read())
{
label.text = (string) reader["myColumn"];
//..... and so on repeating for all the columns in the DB.
}
Yet I've tried using IDataRecord to put all the row values in the list but it gives me NULL.
if (reader.HasRows)
{
List<string> list = (from IDataRecord r in reader
select (string)r["FieldName"]).ToList();
}
But this returns a NULL. Anyone can redirect me to proper piece of information will highly be regarded.
SqlDataReader requires you to read and move the pointer one row by one row. If you want to get all the data at once, you could use SqlDataAdapter and DataTable.
SqlConnection con = new SqlConnection("connection string");
con.Open();
SqlCommand cmd = new SqlCommand("select top 10 documentid from document order by 1 desc", con);
SqlDataReader dr = cmd.ExecuteReader();
List<string> docids = (from IDataRecord r in dr select (string)r["documentid"]).ToList<string>();
con.Close();

Error converting nvarchar to int in ExecuteNonQuery

I am getting an error for the following program in asp.net.
I have checked sql and name is in nvarchar.
{
con.Open();
SqlCommand cmd = new SqlCommand("bookinsertion2", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#idnumber",txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#year", txtyear.Text);
cmd.Parameters.AddWithValue("#department", txtdepart.Text);
cmd.Parameters.AddWithValue("#bookname", ddlbookavail.SelectedItem.ToString());
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/LendingForm2.aspx");
}
This is the code of the stored procedure
create Procedure [dbo].[bookinsertion2]
#idnumber int,
#name nvarchar(20),
#year int,
#department nvarchar(30),
#bookname nvarchar(25)
as
Begin
insert into tbllendinginfo values(#idnumber,#name,#year,#department,#bookname)
insert into tbllendinginfo(Dateofbooktaken) values(GETDATE())
update tblbookinfo set BooksAvailable=BooksAvailable-(select COUNT(Id) from tbllendinginfo where BookName=#bookname) where Name=#bookname
end
The error is " Conversion failed when converting the nvarchar value 'Mike' to data type int. "
The error message is clear, one or more of the parameters expected by the stored procedure are not of type nvarchar. Probably the #year and #idnumber parameters are an integers. If that's true then you need to call
cmd.Parameters.AddWithValue("#idnumber",Convert.ToInt32(txtid.Text));
cmd.Parameters.AddWithValue("#year", Convert.ToInt32(txtyear.Text));
Said that, please try, if possible to avoid the call to AddWithValue, in particular in case where strings or date are involved. AddWithValue determines the type of the parameter from the input value and most of the time is correct, but there are situations where it decides for a wrong datatype and the errors are difficult to find. Moreover AddWithValue with strings is a performance hurdle.
A better explanation could be found in these two articles.
Can we stop using AddWithValue() already?
How Data Access Code Affects Database Performance
You could rewrite the code above using the Object Initializer Syntax
{
con.Open();
SqlCommand cmd = new SqlCommand("bookinsertion2", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#idnumber",
SqlDbType = SqlDbType.Int,
Value = Convert.ToInt32(txtid.Text)
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#name",
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = txtname.Text
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#year",
SqlDbType = SqlDbType.Int,
Value = Convert.ToInt32(txtyear.Text)
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#department",
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = txtdepart.Text
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#bookname",
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = ddlbookavail.SelectedItem.ToString()
});
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/LendingForm2.aspx");
}
EDIT
After your edit I think the problem is in this line of the stored procedure:
insert into tbllendinginfo values(#idnumber,#name,#year,#department,#bookname)
You haven't specified the columns' names but just the parameters. So the server inserts the parameter following the order of definition of the columns in the datatable.
Of course, if the second column in the table is not the column that should receive the #name parameter you could have serious problems.
You could fix the problem listing the name of the columns in the same order iun which you put the parameter inside the VALUES clause or changing the order of the parameters to follow the order of the column names.
For example (I don't know the column names so you should fix them)
insert into tbllendinginfo (idnumber, name, bookyear, department, bookname)
values(#idnumber,#name,#year,#department,#bookname)

System.Data.SqlClient.SqlException: Invalid column name

Trying to do a recordset, I just want one column of data, but this code is giving me an error.. I'm an ASP.NET newb, can anyone help?:
System.Data.SqlClient.SqlException: Invalid column name
'CustomerName'.
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
string CustomerName = "CustomerName";
}
}
String EncCustomerName = Encrypt(CustomerName.Replace(".", "").Replace("-", ""),"1");
Question #2: How do I bind the database content to the CustomerName string? It seems like its only returning "CustomerName" as the value for CustomerName string.. I would like it to return the database data for CustomerName string.. Help?
Suggested to use a ExecuteScalar, so i modified the request to this
using (var con = new SqlConnection(DB.GetDBConn()))
using (var cmdContrib = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID=" + ThisCustomer.CustomerID, con))
{
con.Open();
string CustomerName = cmdContrib.ExecuteScalar();
}
And i Get this error:
"string CustomerName = cmdCust.ExecuteScalar();"
CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
To answer your second question:
// Set it here so you can access it outside the scope of the using statement
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
while (dr.Read())
CustomerName = dr["CustomerName"].ToString();
}
}
}
If you're sure you'll only get one CustomerName result, using a DataReader is a bit of an overkill.
SqlCommand.ExecuteScalar Example
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
SqlCommand cmd = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID = " + Customer.CustomerID, con);
cmd.CommandType = CommandType.Text;
con.Open();
CustomerName = Convert.ToString(cmd.ExecuteScalar());
}
SqlCommand.ExecuteScalar Method
Additional Info
ExecuteScalar returns an object, so you'll need to convert the returned value to the proper type (in this case, string).
Also, you should declare your CustomerName value outside of the using blocks (as I did in my example) - otherwise it will be scoped to the using blocks and not available outside of them.
It means that either CustomerName or CustomerID is not a valid column within your database. Check your table again.
Make sure you are trying to connect correct database.
See CustomerName column should be in Customer table. check spelling also
First, debug and check the value of:
DB.GetDBConn()
You will verify that you are going to the same in Studio as you are in the program.
I think it is the spelling somewhere between the db and your code.
Once you get past the error, you need to fix this:
{
string CustomerName = "CustomerName";
}
You are not accessing the reader, try some kind of tutorial for that stuff.
Try doing a select * from customer where ... and put a breakpoint on your using datareader statement. Then use quick-watch on the datareader object to investigate the columns exposed in the recordset.
Or you could run the select statement on your db of choice to ensure that the column name is the same.
I agree with Madhur above, your column name is not spelled correctly. Or you are not connecting to the correct db.
Hope this helps

Resources