I am trying to get the selectedindex of listbox 1 and 2 and update my databasetable based on the values selected in the two listboxes, but can't find a way to get the selectedindexes into my sql statement. Any suggestions?
private void Form1_Load(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter(
"select * from reservasjon WHERE Rom_nr IS NULL ", dbconn);
adapter.Fill(ds);
this.listBox1.DataSource = ds.Tables[0];
this.listBox1.DisplayMember = "Rnr";
}
private void button1_Click(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds2 = new DataSet();
MySqlDataAdapter adapter2 = new MySqlDataAdapter(
"select * from rom WHERE etasje = '1' AND opptatt='1'", dbconn);
adapter2.Fill(ds2);
this.listBox2.DataSource = ds2.Tables[0];
this.listBox2.DisplayMember = "Rom_nr";
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = listBox1.SelectedIndex.ToString();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string value2 = listBox2.SelectedIndex.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='102' WHERE Rnr='2';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
This should do the trick :
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='"+value2+"' WHERE Rnr='"value1+"';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
That's cause your variable value1 and value2 is not available outside the event handler method since you made them local. Declare them globally or just use the listBox1.SelectedIndex.ToString() directly in your SQL query
Related
System.Data.SqlClient.SqlException: Conversion failed when converting
the varchar value 'System.Data.DataRowView' to data type int.
How to convert?
public partial class FrmItems : MaterialSkin.Controls.MaterialForm
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Users\Admin\source\repos\Elektrokalkulace\Sklad.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter dt;
DataTable dtCategories = new DataTable();
DataTable dtSubCategories = new DataTable();
DataTable dtItems = new DataTable();
public FrmItems()
{
InitializeComponent();
dt = new SqlDataAdapter("SELECT * FROM Categories", conn);
dt.Fill(dtCategories);
CbxCat.DataSource = dtCategories;
CbxCat.DisplayMember = "NameCat";
CbxCat.ValueMember = "CatId";
var skinManager = MaterialSkinManager.Instance;
skinManager.AddFormToManage(this);
skinManager.Theme = MaterialSkinManager.Themes.DARK;
skinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
private void FrmItems_Load(object sender, EventArgs e)
{
// TODO: Tento řádek načte data do tabulky 'skladDataSet.Items'. Můžete jej přesunout nebo jej odstranit podle potřeby.
this.itemsTableAdapter.Fill(this.skladDataSet.Items);
}
private void CbxCat_SelectedIndexChanged(object sender, EventArgs e)
{
dtSubCategories.Clear();
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId='"+ CbxCat.SelectedValue +"'", conn);
dt.Fill(dtSubCategories);
CbxSubcat.DataSource = dtSubCategories;
CbxSubcat.DisplayMember = "NameSubCat";
CbxSubcat.ValueMember = "SubCatId";
}
private void CbxSubcat_SelectedIndexChanged(object sender, EventArgs e)
{
dtItems.Clear();
dt = new SqlDataAdapter("SELECT * FROM Items WHERE SubCatId='" + CbxSubcat.SelectedValue + "'", conn);
dt.Fill(dtItems);
dataGridViewItem.DataSource = dtItems;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FrmHlavniMenu menu = new FrmHlavniMenu();
menu.Show();
this.Hide();
}
}
You claim it is failing on the second line below?
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId='"+ CbxCat.SelectedValue +"'", conn);
dt.Fill(dtSubCategories);
If CatId is an INT then this will fail because of the apostrophes (') surrounding the value. And please use parameters:
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId = #CatId", conn);
dt.SelectCommand.Parameters.AddWithValue("#CatId", CbxCat.SelectedValue);
dt.Fill(dtSubCategories);
Secondly, what is the type of CbxCat.SelectedValue? If it returns a string then you will need to parse the value as an integer: int.Parse(CbxCat.SelectedValue)
But the exception suggests it is actually of type System.Data.DataRowView. In that case you need to access the the item property, for example, CbxCat.SelectedValue["CategoryId"]
See for more info on DataRowView:
https://learn.microsoft.com/en-us/dotnet/api/system.data.datarowview.item?view=netframework-4.8#System_Data_DataRowView_Item_System_String_
I finally solved it this way. It took me a lot of effort, but it was worth it. Thank you all for your support and thank you very very much.
enter code here
public partial class FrmItems : MaterialSkin.Controls.MaterialForm
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Users\Admin\source\repos\Elektrokalkulace\Stock.mdf;Integrated Security=True;Connect Timeout=30");
int CatId;
public FrmItems()
{
InitializeComponent();
refreshCat();
var skinManager = MaterialSkinManager.Instance;
skinManager.AddFormToManage(this);
skinManager.Theme = MaterialSkinManager.Themes.DARK;
skinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
private void FrmItems_Load(object sender, EventArgs e)
{
}
private void refreshCat()
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Categories", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
CbxCat.DisplayMember = "NameCat";
CbxCat.ValueMember = "CatId";
CbxCat.DataSource = dt;
}
private void CbxCat_SelectedIndexChanged(object sender, EventArgs e)
{
if (CbxCat.SelectedValue.ToString() != null)
{
CatId = Convert.ToInt32(CbxCat.SelectedValue.ToString());
refreshSubcat(CatId);
}
}
private void refreshSubcat(int CatId)
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Subcategories WHERE CatId=#CatId", conn);
cmd.Parameters.AddWithValue("CatId", CatId);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
CbxSubcat.DisplayMember = "NameSubcat";
CbxSubcat.ValueMember = "SubcatId";
CbxSubcat.DataSource = dt;
}
private void CbxSubcat_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Items WHERE SubCatId='" + CbxSubcat.SelectedValue + "'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
dataGridViewItem.DataSource = dt;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FrmMainMenu menu = new FrmMainMenu();
menu.Show();
this.Hide();
}
}
enter code here
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=SARManagement;Data Source=AIZAZ\SQLEXPRESS");
con.Open();
string query = "Select Semester,ID FROM Batch";
SqlCommand da = con.CreateCommand();
da.CommandText = query;
SqlDataAdapter adapter = new SqlDataAdapter(da);
DataSet ds = new DataSet();
adapter.Fill(ds, "Batch");
Semester.ItemsSource = ds.Tables[0].DefaultView;
Semester.DisplayMemberPath = ds.Tables[0].Columns["Semester"].ToString();
Semester.SelectedValuePath = ds.Tables[0].Columns["ID"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
here how can i get combobox items.. that are listed in combobox as displaymemberpath
}
how do I get combobox items which is retrieved from database as displaymemberpath ... or share another way to retrieve data and insert data as listboxitem
The DisplayMemberPath and SelectedValuePath should only have a string with the name of the corresponding column. Try this out:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=SARManagement;Data Source=AIZAZ\SQLEXPRESS");
con.Open();
string query = "Select Semester,ID FROM Batch";
SqlCommand da = con.CreateCommand();
da.CommandText = query;
SqlDataAdapter adapter = new SqlDataAdapter(da);
DataSet ds = new DataSet();
adapter.Fill(ds, "Batch");
Semester.ItemsSource = ds.Tables[0].DefaultView;
Semester.DisplayMemberPath = "Semester";
Semester.SelectedValuePath = "ID";
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataRowView data = (DataRowView)Semester.SelectedItem;
string selstr = data["Semester"].ToString();
int sel = (int)data["ID"];
MessageBox.Show("ID: " + sel + " Value: " + selstr);
}
i am facing a problem do not know how to set this problem the problem is that my project working fine but when i delete all the rows from sql databse its not show grid kindly help
your response will be highly appreciated
Here is my Code Behind
public partial class Web_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
using (connection)
{
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
No need of cmd.ExecuteNonQuery(); in BindData Method, As you are not performing any insert,delete or update operation.
try to add this property to your aspx gridview
EmptyDataText="someText"
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
or you can use EmptyDataTemplate - just like TemplateField
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate(v=vs.110).aspx
Good day to all. I have this code that populates the Datagridview. And I tried to edit it. But it seems I can't save any changes to database. Though I'm not getting any errors. Any help would be much appreciated. Thanks alot!
private void FrmViewCustomer_Load(object sender, EventArgs e)
{
string query = "SELECT CONCAT(firstname,', ',lastname) AS NAME, orderedgood AS OrderedGood FROM customer c;";
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
{
conn.Open();
using (MySqlCommand command = new MySqlCommand(query, conn))
{
using (adapter = new MySqlDataAdapter(command))
{
dataGridView1.Rows.Clear();
dataGridView1.AllowUserToAddRows = false;
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
this.adapter.Update(dt);
}
MyTable
id name
1 John
2 Carl
3 Sam
C# Code behind:
public partial class Form1 : Form
{
DataTable dt = null;
DataGridView dgv = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select * from MyTable;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv = new DataGridView();
dgv.AllowUserToAddRows = false;
dgv.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv.Dock = DockStyle.Fill;
dgv.DataSource = dt;
this.Controls.Add(dgv);
}
void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 0)
{
dgv.CancelEdit();
}
}
void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["id"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value+"";
string sql = string.Format("UPDATE `MyTable` SET `{0}` = '{1}' WHERE ID = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
I made a DataGridViewTextBoxColumn called "prod" which lists all products names and ids.
Now I am trying to make DataGridViewTextBoxColumn which get the price of the product selected from DataGridViewTextBoxColumn.
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("select First_Name,Customer_id from customers",con);
SqlDataAdapter Adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
Adapter.Fill(ds,"customers");
comboBox1.DataSource = ds.Tables["customers"];
comboBox1.DisplayMember = "First_Name";
comboBox1.ValueMember = "Customer_id";
SqlConnection cons = new SqlConnection(constring);
SqlCommand cmds = new SqlCommand("select product_id,Product_Name from Products", cons);
SqlDataAdapter Adapters = new SqlDataAdapter(cmds);
DataSet dss = new DataSet();
Adapters.Fill(dss, "Products");
//DataGridViewComboBoxColumn prod = new DataGridViewComboBoxColumn();
prod.DataSource = dss.Tables["Products"];
prod.DisplayMember = "Product_Name";
prod.ValueMember = "product_id";
dataGridView1.Columns.Add(prod);
price_txt = new DataGridViewTextBoxColumn();
price_txt.HeaderText = "price";
price_txt.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns.Add(price_txt);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//SqlConnection cons = new SqlConnection(constring);
//string cmdstring = string.Format("select Price from products where product_id='{0}'",id);
//SqlCommand cmd = new SqlCommand(cmdstring,cons);
//con.Open();
SqlConnection cons = new SqlConnection(constring);
if (e.ColumnIndex ==0)
{
//SqlConnection cons = new SqlConnection(constring);
int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
string cmdstring = "select Price from Products where product_id= "+id;
SqlCommand cmd = new SqlCommand(cmdstring, cons);
cons.Open();
int p = Convert.ToInt32(cmd.ExecuteScalar());
dataGridView1.Rows[e.RowIndex].Cells[1].Value = p;
cons.Close();
}
You could add CellValueChanged event handler for your DataGridView control and then do something like this:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if(dataGridView1.Columns[ e.ColumnIndex] is DataGridViewComboBoxColumn)
dataGridView1.Rows[e.RowIndex].Cells[iTextBoxColumn].Value = ((DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).ValueMember;
}