fill dropdown list by querystring - asp.net

I Had Drop down list and I want to fill it with data from database through stored procedure
and it had it,s value when specific query string I had two query string.
as
private void LoadWithCategory()
{
if (Request.QueryString["Category_Id"] != null)
{
using (SqlConnection Con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetProducFamilyTP", Con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#Category_Id", Request.QueryString["Category_Id"]));
SqlDataReader DR = Com.ExecuteReader();
if (DR.Read())
{
DDLProductFamily.DataSource = DR;
DDLProductFamily.DataTextField = DR["Name"].ToString();
DDLProductFamily.DataValueField = DR["ProductCategory_Id"].ToString();
DDLProductFamily.DataBind();
}
DR.Close();
}
}
}
ALTER Proc GetProducFamilyTP
(
#Category_Id Int
)
AS
Select Distinct Categories.Category_Id ,ProductCategory.Name ,
ProductCategory.ProductCategory_Id
From Category_ProductCategory
Inner Join Categories
On
Category_ProductCategory.Category_Id=Categories.Category_Id
Inner Join ProductCategory
On
Category_ProductCategory.ProductCategory_Id=ProductCategory.ProductCategory_Id
Where
Categories.Category_Id =#Category_Id
but this error occurred
DataBinding: 'System.Data.Common.DataRecordInternal' does not contain a property with the name '4Door'.

The error was in ddl list when I removed it it worked well it had value=0

Related

Getting error from accessing DataReader value (accessing joined table results in SqlDataReader)

UPDATE - PROBLEM SOLVED
Just in case to retrieve all data at once, using a single SQL statement to retrieve joined table results, but couldn't access it and received error below
Exception details: System.IndexOutOfRangeException: crsName
By the way, anyone please suggest a more convenient way to deal with a GridView that need to display a JOIN result.
Instead of this approach - https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.datacontrolfieldcollection.add?view=netframework-4.8
BoundField courseBF = new BoundField();
courseBF.DataField="courseName";
courseBF.HeaderText="Course Name";
//Which is stated in Microsoft Document
Here's the code receive error
string userID = (string)Session["userID"];
string sql = "SELECT courseID from gpaSem where stuID=#userID";
string temp = "";
string temp02 = "";
string[] crsID;
string[] crsName;
string[] grade;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#userID", userID);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
temp += ("!" + dr["courseID"]);
}
crsID = temp.Split('!');
crsID = crsID.Skip(1).ToArray();//course ID get
dr.Close();
con.Close();
con.Open();
temp = "";
foreach (string crs in crsID)
{
sql = "SELECT G.grade AS grade, C.crsName AS crsName FROM gpaSem G, course C WHERE G.courseID=C.courseID AND G.courseID=#courseID";
cmd.Parameters.AddWithValue("#courseID", crs);
dr = cmd.ExecuteReader();
if(dr.Read())
{
temp += "!" + dr["crsName"];//error
temp02 += "!" + dr["grade"];
}
}
crsName = temp.Split('!');
crsName = crsName.Skip(1).ToArray();//course name get
grade = temp02.Split('!');
grade = grade.Skip(1).ToArray();//grade get
dr.Close();
con.Close();
My point is, is that I should explicitly use JOIN in SQL statement or the way I access the value is wrong?

asp SQL Statement to insert multiple rows of record into Table

I am trying to create an attendance table to record down the activities the students have participated. The code below is triggered when a new activity is created. When a new activity is created, I want to insert all the student record into attendance table and mark the default attend attribute as false. (the attend attribute is to mark attendance, sets as 0)
The problem is that the attendance table cannot be populated. The code will stop proceeding at the line: numofRecordsAffected = command.ExecuteNonQuery();
I am trying to get the all the sigstudentid(s) from the Student table. I do not know if the usage of foreach() is recommended in this case, but any help will be appreciated.
I need a solution!
public int InsertAttendance(int num)
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
SqlConnection connect = new SqlConnection();
DataSet dataset = new DataSet();
String sqlText = "SELECT * FROM Student";
connect.ConnectionString = "Data Source=TECKISTTLE; Initial Catalog=Assignment; Integrated Security=True";
command.Connection = connect;
command.CommandText = sqlText;
int numofRecordsAffected = 0;
adapter.SelectCommand = command;
connect.Open();
adapter.Fill(dataset, "StudentData");
sqlText = "";
foreach (DataRow item in dataset.Tables["StudentData"].Rows)
{
sqlText += " INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) VALUES(#SIGStudentID,#ActivityId,#Attendance); ";
command.Parameters.Clear();
command.Parameters.Add("#SIGStudentID", SqlDbType.Int);
command.Parameters["#SIGStudentID"].Value = Convert.ToInt32(item["SIGStudentID"]);
command.Parameters.Add("#ActivityId", SqlDbType.Int);
command.Parameters["#ActivityId"].Value = num;
command.Parameters.Add("#Attendance", SqlDbType.Bit);
command.Parameters["#Attendance"].Value = 0;
}
numofRecordsAffected = command.ExecuteNonQuery();
connect.Close();
return numofRecordsAffected;
}
As you put the code numofRecordsAffected = command.ExecuteNonQuery(); out side your foreach.
It just execute one time. As this code is actual statement to INSERT data in to the table, it will INSERT only one ROW the last one.
Just try to put your code
numofRecordsAffected = command.ExecuteNonQuery();
inside the foreach block. Then it will INSERT each row.
public int InsertAttendance(int num)
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
SqlConnection connect = new SqlConnection();
DataSet dataset = new DataSet();
String sqlText = "SELECT * FROM Student";
connect.ConnectionString = "Data Source=TECKISTTLE; Initial Catalog=Assignment; Integrated Security=True";
command.Connection = connect;
command.CommandText = sqlText;
int numofRecordsAffected = 0;
adapter.SelectCommand = command;
connect.Open();
adapter.Fill(dataset, "StudentData");
sqlText = "";
numofRecordsAffected = 0;
sqlText = "INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) VALUES(#SIGStudentID,#ActivityId,#Attendance); ";
command.CommandText = sqlText;
foreach (DataRow item in dataset.Tables["StudentData"].Rows)
{
command.Parameters.Clear();
command.Parameters.AddWithValue("#SIGStudentID", Convert.ToInt32(item["SIGStudentID"]);
command.Parameters.AddWithValue("#ActivityId", num);
command.Parameters.AddWithValue("#Attendance", 0);
numofRecordsAffected += command.ExecuteNonQuery();
}
connect.Close();
return numofRecordsAffected;
}
You're probably over complicating it a bit by using a loop and could do something like this instead:
"INSERT INTO Attendance(SIGStudentID, ActivityId, Attendance) select SIGStudentID, " + num + " as ActivityId, 0 as Attendance from Student;"
Reference:
insert one column data from a table into other table, but the other column data will be specified dynamically
Insert all values of a table into another table in SQL

binding dropdownlist values to textbox

When the user selects an order ID, the rest of the order information is displayed in label(s). Display the following: employee ID, order date, freight, shipped name, and country. This functionality should be implemented using direct data access programmatically.
Edit: code example and additional explanation.
String CS = onfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionStr‌​ing;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "OrderID";
DropDownList1.DataValueField = "OrderID";
DropDownList1.DataBind();
Label1.Text = Convert.ToString(DropDownList1.SelectedItem.Text);
}
What I want is the other fields which are there in orders table to be displayed when a value is selected in the dropdownlist.
Can you make datatable from the SQL Query result, and then add items to dropdownlist from ID column. When you then select an item from DDL, you show the info where the row from datatable match the selected orderID.
I can write code if you want it isn't cleared what I'm meaning.
UPDATE: with code
var ds = new DataSet();
using (var conn = new SqlConnection(connection))
{
conn.Open();
var command = new SqlCommand("Your SQL Query", conn);
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
conn.Close();
} //Now you have a dataset, with one table that matches your query result.
//And now we can use a foreach loop to add every OrderID to dropdownlis
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DDLname.Items.Add(dr[0].ToString());
}
}
//onSelectedValue event
string orderID = DDLname.Text.toString();
Label1.Text = orderID;
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if(dr[0].toString().equals(orderID))
{
Label2.text = dr[1].toString();
Label3.text = dr[2].toString();
etc....
}
}
}
As you labelled your question with ASP.Net, I assume that this is part of an ASP.Net Webforms application. This means that the drop down list will be inside a web page in a browser. Not clear to me is whether you want the label to be displayed immediately when the user select the item, or only after a post to the server.
In the first case, you'll need javascript and probably something like Ajax or JSON to get the data you want to display for the selected item. In the second case, you could add an event handler for the SelectedIndex_Changed Event of your drop down list. This handler should do something like this:
string CS = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders WHERE OrderId = #OrderId", con);
cmd.Parameters.AddWithValue("#OrderId", DropDownList1.SelectedItem.Value);
con.Open();
if (reader.Read())
{
SqlDataReader reader = cmd.ExecuteReader();
Label1.Text = String.Format("Employee ID: {0}, order date: {1}, freight: {2}, shipped name: {3}, and country {4}."
, reader["employeeid"].ToString()
, reader["orderdate"].ToString()
, reader["freight"].ToString()
, reader["shipname"].ToString()
, reader["shipcountry"].ToString());
}
}

two select query in one stored procedure

i want to select two queries from 1 stored procedure....my following query is correct? and how to call this in 2 gridview
create procedure tablename
#id varchar(50)
as
select a.id,
isnull(a.advance,0) as advance,
isnull(b.submitted_amt,0) as submitted
into #temp1
from
(select id,SUM(Amount)as advance
from table1 where type='Travel' group by id) a
full join
(select id,SUM(Amount)as submitted_amt
from table2 group by categeoryid) b
on a.id=b.id
select id,
advance,
submitted,
advance-submitted as balance_return
from #temp1
select categeoryid,advance,submitted,advance-submitted as balance_return from #temp1 id=#id
Please use this sample:
private void GetMultiSelect()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "AllDetail";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter sqlParam = cmd.Parameters.Add("#Id", SqlDbType.Int, 4);
sqlParam.Value = 1;
//dataset object to get all select statement results
DataSet ds = new DataSet();
//sql dataadoptor to fill dataset
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
//here all select statements are fill in dataset object
adp.Fill(ds);
//now u can fetch each and every select statement by providing table index in dataset
foreach (DataTable dt in ds.Tables)
{
//select statement result in dt..
}
//or instead of loop u can specify the index
GridView1.DataSource= ds.Tables[1]; // first select statement result
GridView1.DataBind();
GridView2.DataSource = ds.Tables[0]; // second select statement result
GridView2.DataBind();
}
}
}
}
Please go to this link for details

sql data reader class

I did sql command with SqlDataReader but I had this error
System.IndexOutOfRangeException: UserName
Page Load event:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("Total", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataReader Dr = Com.ExecuteReader();
if (Dr.Read())
{
string Result= Dr["UserName"].ToString();
Lbltotal.Text = Result;
}
}
}
Stored Procedure:
Alter proc Total
as
begin
select Count (UserName) from Registration
end
Change your storder procedure to:
Alter proc Total
as
begin
select Count (UserName) as UserName from Registration
end
You're not returning any column called UserName - you're just returning a count which has no explicit column name.
If you have something like this - just a single value - you could also use the ExecuteScalar method which will return exactly one value:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
int count = (int)Com.ExecuteScalar();
}
If you insist on using the SqlDataReader, you just need to use a positional parameter:
using(SqlCommand Com = new SqlCommand("Total", con))
{
Com.CommandType = CommandType.StoredProcedure;
using(SqlDataReader Dr = Com.ExecuteReader())
{
if (Dr.Read())
{
string Result= Dr[0].ToString(); // take value no. 0 - the first one
Lbltotal.Text = Result;
}
}
}

Resources