About C# in ASP.NET and SQL Server - c#

I have a drop down list that binding data from database table and I can show it, but when I wanna show the data when I selected the drop down list value, it can't show anything
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = GetData();
DropDownList1.DataTextField = "DEPT_NAME";
DropDownList1.DataValueField = "DEPT_NO";
DropDownList1.DataBind();
}
}
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = DropDownList1.SelectedValue;
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
{
using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value, conn))
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
this.GridView1.Visible = true;
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
conn.Close();
}
}
}
DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
{
using (SqlCommand cmd = new SqlCommand("SELECT 'Please Select' AS DEPT_NAME , '000' AS DEPT_NO UNION SELECT DEPT_NAME , DEPT_NO FROM dept ORDER BY DEPT_NO ASC", conn))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
return dt;
}

using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO = #value", conn))
cmd.Parameter.AddWithValue("#value",value);
Query ( "SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value) will work if DEPT_NO dataType is number

Related

Dropdownlist Selected Item is not showing correct item

// fill from database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values (N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
I fill a Dropdownlist from SQL Server, then send selected item to another table in SQL Server; but it send first item of Dropdownlist as selected item.
Selected item didn't change and returns default value.
The reason is obvious, you are filling the dropdown list and then inserting the record, so it is bound to take the first item of the DropdownList.
I would suggest you separate the code of filling the dropdown list in another function and do the insertion only on selected_index change (ddl_SelectedIndexChanged) of DropDownList. In this ddl_SelectedIndexChanged function just check the selected value of the drop-down list and insert it to your target table (please remember to not invoke the call the function to load/Fill Dropdown List which you are currently doing in the shared code snippet).
SomeThing Like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
}
}
protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
{
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values
(N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Hope this Helps!
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Loading Dropdown by calling This.
LoadDdl();
}
}
//Load Dropdown From Database.
protected void LoadDdl(){
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
}
//Inserting Item to another table by selected index change.
protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
{
//Checking If it's not the default value.
if(ddlUser.SelectedIndex != -1){
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values
(N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

Procedure or function 'select1_customer' expects parameter '#Customerid', which was not supplied

This is my code :
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
mytable = new DataTable();
mytable.Columns.Add("Customerid");
mytable.Columns.Add("Customername");
mytable.Columns.Add("Contactname");
mytable.Columns.Add("Address");
mytable.Columns.Add("Mobile");
GridView1.DataSource = mytable;
GridView1.DataBind();
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
//SqlCommand cmd = new SqlCommand("select * from Table_3", con);
SqlCommand cmd = new SqlCommand("select1_customer", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(mytable);
GridView1.DataSource = mytable;
GridView1.DataBind();
}
}
Procedure or function 'select1_customer' expects parameter '#Customerid', which was not supplied. it was my error
Your are missing
cmd.Parameters.AddWithValue("#Customerid", required value);
Try,
SqlCommand cmd = new SqlCommand("select1_customer", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Customerid", "value_for_CustomerID");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(mytable);
GridView1.DataSource = mytable;
GridView1.DataBind();

How to display SQL search results in a datagrid using WPF

private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
string sql;
{
sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
{
grdSearch.ItemsSource = sql;
sc.Close();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
Problems:
SQL query is not right:
It should be like SELECT * FROM TABLENAME.
In WHERE clause [Forename] == 'txtSearch.Text', == should = and Textbox value should be concatenated using +.
Fixed Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sConn = #"Data Source=MYDS;Initial Catalog=MyCat;
User ID=MyUser;Password=MyPass;";
using(SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= #Forename";
SqlCommand com = new SqlCommand(sql, sc);
com.Parameters.AddWithValue("#Forename", txtSearch.Text);
using(SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
}
}
Use this
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Employee");
sda.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}

id getting inserted without selecting in c#.net

private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
In the first class i have a combobox and i am fetching its value from database and i have shown "Select Project Name" on page load in combobox.I want to insert its value only when user selects option from dropdown and insert nothing if user did not choose any option.
Now the problem is that the first name in the dropdown gets inserted on button click.without choosing any option.I want that if user did not choose any name value from dropdown nothing should get inserted.
can anyone help me..?
Assuming that datatype of ID column is int:
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
//begin adding line
DataRow row = table.NewRow();
row["project_name"] = "Select Project Name";
row["ID"] = 0;
table.Rows.InsertAt(row, 0);
//end adding line
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
if(combo_status.SelectedValue == 0)
{
return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
}
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Hope this will help you

Fill DropDownList from database

I am new to C# and trying to populate a DropDownList based on a database value. I tried connecting to database as shown below - tested with the statement and it says connected. Can I assume this is correct? Am I on the right track? Also, how do I then select value from the table and fill DropDownList with a field?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
connection.Open();
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
SqlDataReader dReader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" +
" order by [Name] asc";
connection.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
//Names collection is a combo box.
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close()
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
Hope that helps................
It's So Much Simple :----
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = #"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];
------------------------------------------------------------------------
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}

Categories