Gridview select row to next page C# - c#

I need to fetch the selected row of Gridview in next page.. I'm getting exception at if (condition) that cannot find table 0 so below is my code.help me out.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
String abc = "Select fname,lname,city,address,empid,email,phone,department from employee Where id=" + Request.QueryString["a"];
SqlCommand cmd = new SqlCommand(abc, con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
**if (ds.Tables[0].Rows.Count > 0)** //getting error at this
{
fname.Text = ds.Tables[0].Rows[0]["fname"].ToString();
lname.Text = ds.Tables[0].Rows[0]["lname"].ToString();
ddl1.SelectedItem.Value = ds.Tables[0].Rows[0]["city"].ToString();
address.Text = ds.Tables[0].Rows[0]["address"].ToString();
empid.Text = ds.Tables[0].Rows[0]["empid"].ToString();
email.Text = ds.Tables[0].Rows[0]["email"].ToString();
phone.Text = ds.Tables[0].Rows[0]["phone"].ToString();
DropDownList1.SelectedItem.Value = ds.Tables[0].Rows[0]["department"].ToString();
}
}

Before the line on error You need to fill your dataset
da.Fill(ds, "MyTable")
EDIT :
You also didn't open your connection
SqlConnection con = new SqlConnection(cs);
//Open the connection
con.Open()
String abc = "Select fname,lname,city,address,empid,email,phone,department from employee Where id=" + Request.QueryString["a"];
SqlCommand cmd = new SqlCommand(abc, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//Fill the dataset
da.Fill(ds, "MyTable")
//Close the connection
con.Close()
...

Related

Change button text with values get from database

I want to change button text with values get from database unfortunately all buttons take the same text
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\ARANL\\Menu.accdb");
con.Open();
//OleDbDataAdapter da = new OleDbDataAdapter("SELECT Nummer,Speisename FROM Pizza", con); bunun bir anlamı yok.
//DataSet ds = new DataSet(); buna da gerek yok bildiğim kadarıyla.
OleDbCommand kmt = new OleDbCommand("SELECT Nummer,Speisename FROM Pizza", con);// o kodu buraya geçtik.
OleDbDataReader oku = kmt.ExecuteReader();
//da.Fill(ds); buna da
//DataTable dt = new DataTable();
var data = new Dictionary <string, object>();
while (oku.Read())
{
data.Add(oku["Nummer"].ToString(), oku["Speisename"].ToString());
}
con.Close();
button50.Text = data["button50"].ToString();
button51.Text = data["button51"].ToString();
button52.Text = data["button52"].ToString();
button53.Text = data["button53"].ToString();
button54.Text = data["button54"].ToString();

Assign query result into a session

i want assign result into a session
c# code
protected void BindData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-677TN4G\SQLEXPRESS;Initial Catalog=homework;Persist Security Info=True;User ID=sa;Password=123456");
DataSet ds = new DataSet();
DataTable FromTable = new DataTable();
con.Open();
string cmdstr = "Select CourseName from Staff where FacultyNumber=#idd";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("#idd", Session["id"].ToString());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
DataList1.DataSource = ds.Tables[0];
DataList1.DataBind();
}
so how i can do it i try to do
Session["id"] = cmdstr.Text;
but it not work
i do it like this but not work
I do it like this
protected void BindData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-677TN4G\SQLEXPRESS;Initial Catalog=homework;Persist Security Info=True;User ID=sa;Password=123456");
DataSet ds = new DataSet();
DataTable FromTable = new DataTable();
con.Open();
string cmdstr = "Select CourseName from Staff where FacultyNumber=#idd";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("#idd", Session["id"].ToString());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
DataList1.DataSource = ds.Tables[0];
Session.Add("Staff", ds.Tables[0]);
DataList1.DataBind();
Label1.Visible = true;
Label1.Text = "Course Name is : " + Session["Staff"].ToString();
}
and the output is
Course Name is : Table
not the selected value
In your case the result is a DataTable no problem you can store this DataTable to the session as well. Let staffData be the DataTable that you are populating from the database,
Session.Add("Staff", staffData); // Adding datatable to the session
In your case you are using ds is used as a DataSet and you are accessing ds.Tables[0] to bind the grid. in this case you can use something like: Session.Add("Staff", ds.Tables[0]);.
Later you may come up with another question that how can I retrieve this DataTable from the session, Here I'm adding the answer for that as well.
DataList1.DataSource = (DataTable)Session["Staff"];

c# how to use Combobox.Value for a From Clause in a Sql query

Please can you assist me in a very weird request
I am building a form to represent a table in a datagridview.
I want to change the data that is bound to the datagridview when i select a different value in a combobox. I bound the event to a button.
i get an error when i run the code:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in query. Incomplete query clause.
the code i have is as follows.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand("Select * From #name ", con);
cmd.Parameters.AddWithValue("#name", comboBox1.SelectedValue);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
This code will help you:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.Text), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
you can not pass table name as parameter. you can build sql based on your value selection in your combobox. replace your code with this code and check.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.SelectedValue), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
If you use Data Bound Items then use comboBox1.SelectedValue. If you use Unbound Mode then use comboBox1.SelectedItem.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
//OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedValue.ToString(), con);
OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedItem.ToString(), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
But not advice this way. You can use stored Procedure.
Try This:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
string tableName = comboBox1.SelectedValue;
var builder = new SqlCommandBuilder();
string escapedTableName = builder.QuoteIdentifier(tableName);
OleDbCommand cmd = new OleDbCommand("Select * From " + escapedTableName , con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}

How to bind data to label in asp.net

I have created a form in asp.net,where i have some textbox, in which I have taken some input which is stored in the database. I have created another page where I have taken the same number of label as the textbox.
I want to show the data in the labels that I last entered.
How can i do that?
Code:
string cs = ConfigurationManager.ConnectionStrings["TrishanConnection"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 coil_id FROM CoilDetails ORDER BY coil_id DESC", con);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
LabeCoilid.Text = ds.ToString();
LabeCoilid.DataBind();
con.Close();
Try instead of
LabeCoilid.Text = ds.ToString();
this
LabeCoilid.Text = ds.Tables[0].Rows[0][0].ToString();
LabeCoilid.Text = ds.Tables[0].Rows[0]["coil_id"].ToString();
You don't need to call DataBind()
string cs = ConfigurationManager.ConnectionStrings["TrishanConnection"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 coil_id FROM CoilDetails ORDER BY coil_id DESC", con))
{
con.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(ds);
dt=ds.Table[0]
}
}
LabeCoilid.Text = dt.Rows[0][0].ToString();
LabeCoilid.DataBind();
con.Close();
You can change the rows and columns by changing dt,Rows[4][8]

sql search query in c#

I'm trying to make a database search in my app where the user would choose the column and enter the search word and the result would come up in a dataviewgrid.
This is the code i've been working on, the problem is that nothing comes up and i'm pretty sure there are entries in the database. EDIT : it's a windows form application
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE #choice = #input", conn);
cmd.Parameters.AddWithValue("#choice", comboBox1.Text);
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
You cannot use a parameter to express the name of a column.
You should populate your combobox with the column names and set its DropDownStyle property to DropDownList (do not allow your user to type the name of the column) and then build your query
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = #input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
you forgot to bind the grid view with datasource
add this after data source
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\albasheer\Desktop\games\my_school\my_school\school.mdf;Integrated Security=True;User Instance=True");
connection.Open();
string sql = "select name,id,stage,age,cost from STUDENT where stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
SqlCommand command = new SqlCommand(sql, connection);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
id = t.Field<int>("id"),
Name = t.Field<string>("name"),
};
bunifuCustomDataGrid1.DataSource = dt.ToList();
}

Categories

Resources