Retrieve data in dropdown from SQL Server database - sql-server

I have two tables, one is dept and the other is emp with primary and foreign key relationship from emp.deptid which is a foreign key to dept.id. I have an aspx webpage and I have a dropdown list on it which I want to use to select dname form dropdown. But when I try to execute this code I get an error
Fill: SelectCommand.Connection property has not been initialized.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{ }
binddeptdropdown();
}
void binddeptdropdown()
{
SqlDataAdapter da = new SqlDataAdapter("select * from dept", con);
DataSet ds = new DataSet();
da.Fill(ds, "dept");
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = "dname";
DropDownList1.DataTextField = "deptid";
DropDownList1.DataBind();
}

Your closing brace on your using function is in the wrong place, and your connection object needs to be passed to your function.
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
binddeptdropdown(con );
}
}
void binddeptdropdown(SQLConnection con)
{
SqlDataAdapter da = new SqlDataAdapter("select * from dept", con);
DataSet ds = new DataSet();
da.Fill(ds, "dept");
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = "dname";
DropDownList1.DataTextField = "deptid";
DropDownList1.DataBind();
}

Related

I need to bound from query row to a label.text

Please look at code below and help me with your experience. I need to pull out company name from query and bound it to the lblCustName.text I tried different method but still I am getting errors. Please help to fix this problem.
public partial class frmMTO : Form
{
static string constring = ConfigurationManager.ConnectionStrings["cfTrack.Properties.Settings.Setting"].ConnectionString;
DataTable mtotbl = new DataTable("tbl");
public frmMTO()
{
InitializeComponent();
}
private void frmMTO_Load(object sender, EventArgs e)
{
btnStart.Enabled = false;
lblCustName.Text = "";
// Binding data to Customers List
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT Quote_No, Company FROM tblRFQ_logs ORDER BY Quote_No DESC", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
cmRFQ.ValueMember = "id";
cmRFQ.DisplayMember = "Quote_No";
cmRFQ.DataSource = dt;
SqlDataAdapter materiaDA = new SqlDataAdapter("SELECT Grade FROM tblMaterialGrades", con);
DataTable materialDT = new System.Data.DataTable();
materiaDA.Fill(materialDT);
cmMaterial.ValueMember = "Grade_id";
cmMaterial.DisplayMember = "Grade";
cmMaterial.DataSource = materialDT;
// Closing Connection
con.Close();
mtotbl.Columns.Add("ID", typeof(int));
mtotbl.Columns.Add("Material", typeof(string));
mtotbl.Columns.Add("Item Mark", typeof(string));
mtotbl.Columns.Add("Short Code", typeof(string));
mtotbl.Columns.Add("Description", typeof(string));
mtotbl.Columns.Add("Unit", typeof(string));
mtotbl.Columns.Add("QTY.", typeof(string));
mtotbl.Rows.Add(1, "SA-106 B", "N1", "PIP4STD106","4in STD SA-106B, SMLS", "in.", "6");
dataGridView1.DataSource = mtotbl;
}
private void cmRFQ_SelectedValueChanged(object sender, EventArgs e)
{
// here I need to change the label text
lblCustName.Text = "Company" <------ this data comes from query
}
Thanks for your reply
Assuming that you bind the selected index change to this function.
cmRFQ.SelectedIndexChanged += new System.EventHandler(list_SelectedIndexChanged);
I think what you're looking for is this:
protected void list_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
string value = (string)list.SelectedValue;
lblCustName.Text = value
}

C#: Windows Form creating table and and retrieve data from database by each dynamic button click

I am trying to develop a restaurant billing application in windows form.
so I created dynamic buttons.
now I need a table which will retrieve data from database for each button click.
How can it possible?
private void newb_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// textBox1.Text = btn.Text;
connection con = new connection();
con.connecting();
// Button b = new Button();
int i = 0;
var query = "select itemname,itemcode,price from item_master where itemcode =" + btn.Name;
MySqlCommand cmd = new MySqlCommand(query, con.con);
while (i < 10)
{
MySqlDataAdapter sda = new MySqlDataAdapter();
DataTable dt = new DataTable();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
// MessageBox.Show(btn.Name);
i++;
}
// sda.Update(dbdataset);
// =dataGridView1.Rows[0]
//// MySqlDataReader mdr;
//// mdr = cmd.ExecuteReader();
// while (mdr.Read())
// {
//// textBox1.Text = (mdr["itemname"].ToString());
// }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}

Get the new added row values for insert in grid control devexpress winform

i'am actually trying to get the new values of the new added row from my grid control (devexpress) thant i set "AllowAddRows" to true;
i can get the updated one like this
Object row = ListeQual.GetRow(ListeQual.FocusedRowHandle);
but i can get the new values in add event for insert
Try this :
private void ListeQual_ValidateRow(object sender, ValidateRowEventArgs e)
{
GridView view = sender as GridView;
if (view.IsNewItemRow(e.RowHandle))
{
DataRow row = view.GetDataRow(e.RowHandle);
}
}
You can create a button how allow to add new row :
private void AddNewRow_Click(object sender, EventArgs e)
{
// (ListeQual.MainView as DevExpress.XtraGrid.Views.Grid.GridView).AddNewRow();
ListeQual.AddNewRow();
}
And a create a methode how you can pass the new row as parameter for saving in datatbase :
private int insertData(DataRow dr)
{
string connectionString = "your connection string here";
int nb = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Col1, Col2, Col3) VALUES (#col1, #col2, #col3)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#col1", dr[0]);
cmd.Parameters.AddWithValue("#col2", dr[1]);
cmd.Parameters.AddWithValue("#col3", dr[2]);
connection.Open();
nb= cmd.ExecuteNonQuery();
}
return nb;
}
Finally you can handle the event ValidateRow :
private void ListeQual_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
{
GridView view = ListeQual as GridView;
if (view.IsNewItemRow(e.RowHandle))
{
DataRow dw = view.GetDataRow(e.RowHandle);
insertData(dw);
}
}

How to generate linkage checkbox (C #)?

initial we will see two checkbox
No.1: Fruit
No.2: Animals
if select checkbox1 then display
□ Bananas
□ Apple
if select checkbox2 then display
□ Dog
□ Cat
□ Monkeys
I do not know how to write it with asp.net(c#), (they begin with SQL binding lists), thank you very much !!!
the initial two checkbox is use
Front End:
<asp:CheckBoxList ID="chkFruit_animal" runat="server"
onload="CheckBoxFruit_animal_Load" >
</asp:CheckBoxList>
Code Behined:
protected void CheckBoxFruit_animal_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sqlstr;
sqlstr = "SELECT DISTINCT * From fa";
MySqlDataAdapter myAdapter = new MySqlDataAdapter();
MySqlConnection dbconn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
DataSet ds = new DataSet();
myAdapter.SelectCommand = new MySqlCommand(sqlstr, dbconn);
myAdapter.Fill(ds, "fa");
chkFruit_animal.DataSource = ds.Tables["fa"];
chkFruit_animal.DataTextField = "faName";
chkFruit_animal.DataValueField = "faID";
chkFruit_animal.DataBind();
}
}
Database:
[fa]
faID|faname
1 |Fruit
2 |Animals
[teamName]
faID|Tname
1 |Bananas
1 |Apple
2 |Dog
2 |Cat
2 |Monkeys
Update code
Front End:
<div>
<div>
<asp:CheckBoxList ID="chkFruit_Animal" runat="server" OnCheckedChanged="chkFruit_Animal_CheckedChanged" ></asp:CheckBoxList>
</div>
<asp:CheckBoxList ID="chkBind" runat="server"></asp:CheckBoxList>
</div>
Code Behined
protected void Page_Load(object sender, EventArgs e)
{
//Console.WriteLine(json);
if (!IsPostBack)
{
//get the data from database
DataTable dtFruitAnimal = new DataTable("Name");
dtFruitAnimal.Columns.Add("faID");
dtFruitAnimal.Columns.Add("faname");
dtFruitAnimal.Rows.Add("1","Fruit");
dtFruitAnimal.Rows.Add("2","Animals");
chkFruit_Animal.DataSource = dtFruitAnimal;
chkFruit_Animal.DataTextField = "faID";
chkFruit_Animal.DataValueField = "faname";
chkFruit_Animal.DataBind();
}
}
protected void chkFruit_Animal_CheckedChanged(object sender, EventArgs e)
{
string value = chkFruit_Animal.SelectedValue;
DataTable dtResult = GetData(value);
chkBind.DataSource = dtResult;
chkBind.DataTextField = "faID";
chkBind.DataValueField = "Tname";
chkBind.DataBind();
}
public DataTable GetData(string strValue)
{
DataTable dt = new DataTable("DtResult");
string sqlQuery = "SELECT DISTINCT * From teamName where faId=#value";
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con))
{
da.SelectCommand.CommandType = CommandType.Text;
da.SelectCommand.Parameters.AddWithValue("#value", strValue);
da.Fill(dt);
}
}
return dt;
}

fill textbox on second combobox selection changed in cascading combobox in windows form using c#

I have 2 cascading combo-box in windows form application. I have textbox for price and unit. when I select first combobox, second combobox gets populated. I want textbox for price and unit to be filled only on second combobox selection.
My problem is when the form is loaded both textboxes are filled with values from table and not on combobox selection changed.
my code is:
private void Purchase_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'supplierDataSet.Supplier' table. You can move, or remove it, as needed.
this.supplierTableAdapter.Fill(this.supplierDataSet.Supplier);
fillName();
comboBoxName.SelectedIndex = -1;
}
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name=#Item_Name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#Item_Name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.DisplayMember = "Item_Make";
}
}
}
}
private void comboBoxName_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text))
{
comboBoxMake.Enabled = true;
fillMake();
comboBoxMake.SelectedIndex = -1;
}
}
private void comboBoxMake_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxMake.Text))
{
textBoxPrice.Enabled = true;
textBoxUoM.Enabled = true;
}
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Item Where Item_Make='" + comboBoxMake.Text + "' AND Item_Name='" + comboBoxName.Text + "'", con);
SqlDataReader reader;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxPrice.Text = Convert.ToString(reader["Price"]);
textBoxUoM.Text = Convert.ToString(reader["Unit"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
I am stuck here. please help.
Try changing SelectedIndex = -1 to SelectedItem = -1 in Purchase_Load and ComboBox1_SelectedIndexChanged.

Resources