Gridview table not being displayed in asp.net webform - c#

I just want to display the gridview with some specific queries.
I've tried doing it below.
This code shows "No data matches" when wrong parameter is passed in query ,but displays nothing even when parameters are correct.
I am new to asp.net .Please tell me,what important line ,I'm missing
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Filter"] = "ALL";
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
string query = "SELECT ContactName, City, Country, PostalCode FROM Customers";
SqlCommand cmd = new SqlCommand("SELECT ContactName, City, Country, PostalCode FROM Customers WHERE Country='UK'" );
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

The code is working and returning 7 rows from northwind database into the gridview.
Your connection string should be like this in web.config file:
<connectionStrings>
<add name="NorthwindConnectionString1" connectionString="server=.; database=northwnd; integrated security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>

Related

How to retrieve and display values in GridView from SQL Server database in ASP.NET using C#

I am creating a web application in Microsoft Visual Studio 2010. I want to retrieve data from a SQL Server database and display it in a GridView in ASP.NET using C#.
I want to retrieve data on button onclick event.
protected void submit_click(object sender, EventArgs e)
{
connection1.open();
SqlCommand sq= new SqlCommand("select student_id
, student_name from student);
SqlDataReader dr= new SqlDataReader();
...
// Gridview
}
Refer for description : Microsoft Visual Studio-how-to-retrieve-and-display-values-from-database-in -ASP.NET-using-C#.
protected void Button1_Click( object sender, EventArgs e) {
//connection string
SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;
AttachDbFilename='C:\Users\HP\Documents\Visual Studio
2010\Projects
\assignment\assignment\App_Data\pokedex.mdf';Integrated
Security=True; User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from pokedex;");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}

"Network path not found"-error in asp.net (C#) in connectionstring

I´d like to know if there is anything wrong in this code because it doesn´t connect to the datasource. If i do it with an SQLDataSource in the aspx file there is no error. But why don´t the commands work within my code-behind .cs-file? I hope you understand my problem because i´m just new in .net-coding.
protected void Page_Load(object sender, EventArgs e)
{
//var conString = ConfigurationManager.ConnectionStrings["ConnectionString"];
//string strConnString = conString.ConnectionString;
string constr = ConfigurationManager.ConnectionStrings["OLEDB"].ConnectionString;
string query = "selectcommand";
SqlConnection conn = new SqlConnection("Data Source=source.com;Persist Security Info=True;Password=xxxxxxxxx;User ID=system");
SqlCommand cmd = new SqlCommand(query, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
}
It says: "Network path not found"
Row 40: da.Fill(ds);
If i add a Provider into the SqlConnection it says: "Keyword not supported: Provider" <-- that´s why i deleted it out of the command.

Saving survey answers to a database

I'm working on a project that requires me to create an evaluation portal (survey) where users login and answer 20 questions and its all rating questions (Strongly Disagree, Disagree, Agree and Strongly Agree).
I'm using ASP.net and C# and radio button list in every page.
I was able to create the login page using sessions.
I wanted to display every question in a separate page but when I do that I start having trouble with saving survey responses to the database. the result for each question get display in a separate row in the database. to be more specific, every user will have 20 rows of data in the database.
My question how to get each user responses in the same line or row in the database??
Any help will be greatly appreciated.
Thanks
Here is my login page:
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Student;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select s.First_Name, s.Last_Name,c.Class_Title, c.Course_ID, c.Instructor_Last, c.Instructor_First, c.Term, c.Section_ID, c.Course_Number,e.Instructor_ID from Student S Join Student_Course e ON (s.Student_ID = e.Student_ID) Join Course c ON(c.Course_ID = e.Course_ID) where UserName =#username and Password=#password",con);
cmd.Parameters.AddWithValue("#username", txtUserName.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["USER_ID"] = dt;
Response.Redirect("Successful_Login.aspx");
}
Here is my successful login page
This page to get user information base on their login, I'm using a gridview to show students courses base on their login and from there they can click on the course they want to rate and start the survey.
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["USER_ID"];
lblName.Text = dt.Rows[0][0].ToString() + " " + dt.Rows[0][1].ToString();//your cloumn name;
DataTable dt2 = (DataTable)Session["USER_ID"];
GridView1.DataSource = dt2;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string instructorName = GridView1.SelectedRow.Cells[4].Text + ", " + GridView1.SelectedRow.Cells[5].Text;
string courseSession= GridView1.SelectedRow.Cells[7].Text + "-" + GridView1.SelectedRow.Cells[8].Text;
string term = GridView1.SelectedRow.Cells[6].Text;
Session["USER_ID"] = instructorName;
Session["USER_ID2"] = courseSession;
Session["USER_ID3"] = term;
Response.Redirect("Q1.aspx");
}
Here is the first question (Q1)
When the user click next button to go the next question, I would like for all response to go to the database and they go to the next page(Q2), I would like to capture all the results in the same row.
protected void btnNext_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Student;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into Survey (Q1,Q1_Comments) values (#Q1,#Q1_Comments)", con);
cmd.Parameters.AddWithValue("Q1", radListQ1.SelectedValue);
cmd.Parameters.AddWithValue("Q1_Comments", txtQ1Comments.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
For starter, if you want to display all 20 responses from the same user in one row, then you should construct a table that has more columns in database.
e.g.
Survey
-----------------------------------------------------
studentID | Q1 | Q1_comments | Q2 | Q2_comments | ...
For the first question Q1, you can still use your original insert statement above:
SqlCommand cmd = new SqlCommand("insert into Survey (Q1,Q1_Comments) values (#Q1,#Q1_Comments)", con);
cmd.Parameters.AddWithValue("Q1", radListQ1.SelectedValue);
cmd.Parameters.AddWithValue("Q1_Comments", txtQ1Comments.Text);
For the second question and onwards, you need to perform update instead of inserting to database. e.g.
SqlCommand cmd = new SqlCommand("UPDATE Survey SET (Q2=#Q2,Q2_comment=#Q2_Comments)", con);
cmd.Parameters.AddWithValue("Q2", radListQ2.SelectedValue);
cmd.Parameters.AddWithValue("Q2_Comments", txtQ2Comments.Text);
As a little bit of advise, you might want to use transaction to do insert,update or delete, and surround them using try ... catch ... detect/handle potential error. More reading from MSDN
Hope this helps.
I strongly suggest you store in 20 rows... But if you insist using just one row.. I would suggest UPDATE command instead of INSERT...
Just to provide the complete code. this is Q1
protected void btnNext_Click(object sender, EventArgs e)
{
if (Session["USER_ID"] != null )
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Student;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into Survey (Q1,Q1_Comments) values (#Q1,#Q1_Comments)", con);
cmd.Parameters.AddWithValue("Q1", radListQ1.SelectedValue);
cmd.Parameters.AddWithValue("Q1_Comments", txtQ1Comments.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
And this is Q2
protected void btnQ2Next_Click(object sender, EventArgs e)
{
if (Session["USER_ID"] != null)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Student;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE Survey SET (Q2 = #Q2, Q2_Comments = #Q2_Comments)", con);
cmd.Parameters.AddWithValue("Q2", radListQ2.SelectedValue);
cmd.Parameters.AddWithValue("Q2_Comments", txtQ2Comments.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Q3.aspx");
}
}

How to insert value from gridview into database

I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}

Errors when retrieving values from database determined by combobox to gridview

I have a code to get all the values from database determined by a combobox to a datagridview.
But whenever i run it , i get invalid column name for ListU.SelectedValue , and the multi-part identifier "System.Data.DataRowView" could not be bound if i am using ListU.SelectedItem.
where did i go wrong? i am guessing it is either my code or it is my table.
private void User_Load(object sender, EventArgs e)
{
SqlDataAdapter daSearch = new SqlDataAdapter("SELECT cName FROM ComDet", conn);
DataTable dt1 = new DataTable();
ListU.DataSource = dt1;
daSearch.Fill(dt1);
ListU.ValueMember = "cName";
ListU.DisplayMember = "cName";
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
}
and the button code -
private void searchBtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName =" + ListU.SelectedValue, conn);
DataTable dts3 = new DataTable();
daS.Fill(dts3);
dataGridView1.DataSource = dts3.DefaultView;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
conn.Close();
}
you should use SqlParameter ... helps against sql injection problems and also against missing quotes ... like this:
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName = #name", conn);
daS.SelectCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = ListU.SelectedValue;
this assumes that cName is a string ... if not you'll have to change the SqlDbType ...

Categories

Resources