Unable to delete rows from DataGrid - c#

Now this may be a "Noob" question. But I cant seem to do any commands that people seem to do with The DataGrid. What is the difference, and why can I only get DataGrid?
My problem is that I am trying to delete rows in the datagrid when they are pulled from a database. But, I cant figure out how because the SelectRows command does not work.
That is what i have so far. Is there anyway i can get DataGrid?
EDIT:
This is how I get information into the datagrid.
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (DataGridViewRow row in userDataGrid.SelectedRows)
{
if (!row.IsNewRow)
dataGridView1.Rows.Remove(row);
}
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=----; Database=----; User id=vsd; password=----";
conn.Open();
dt = new DataTable();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(dt);
userDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
Also, If there is a better way to do this, please let me know as well. I am very new to all of this.

Use the same instance of DataTable every time when you pull rows from db.
DataTable mDataTable = new DataTable(); //class field
public Constructor()
{
InitializeComponent();
userDataGrid.ItemsSource = mDataTable .mDataTable;
}
void PullData()
{
mDataTable.Clear();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(mDataTable );
}
}
It should solve your problem, but it's bad approach.
As Bizz adviced look at MVVM pattern & entity framework.

This is what I ended up doing for deleting the button. Most answers were trying to answer to a DataGridView. But, This is not WinForms or a DataGridView. This is WPF and its just DataGrid.
This is what I did to delete the row from the grid and the database.
private void delete_Click(object sender, RoutedEventArgs e)
{
DataGrid dg = this.aSSIGNMENTDataGrid;
var id1 = (DataRowView)dg.SelectedItem; //Get specific ID From DataGrid after click on Delete Button.
PK_ID = Convert.ToInt32(id1.Row["AssignmentID"].ToString());
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "delete from ASSIGNMENT where AssignmentID='" + PK_ID + "' ";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
filldatagrid();
}
private void filldatagrid()
{
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "select * from ASSIGNMENT";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
aSSIGNMENTDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
}

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();
}
}

How To delete from both database and datagridview

So i've been looking around the google for the anwser to this found so many diffrenet anwsers but i do not quite understand them and dont really see the way to implement them even thoug i have tryed alot so my issue is basicly that my delete button only deletes from the datagridview and not the database itself i do have the gridview bound to my knowledge but this is the very first form app i make so im a bit puzzeld to what i am doing
private void buttonDel_Click(object sender, EventArgs e)
{///////////////////////////////////////////////////////issue is here
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
//string del = "DELETE FROM Data WHERE RowID = #RowID";
}
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
string query = "insert into data(Navn, NummerPlade, KMKørt, dato)";
query += " values (#Navn, #NummerPlade, #KMKørt, #dato)";
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.AddWithValue("#Navn", textBox1.Text);
cmd.Parameters.AddWithValue("#NummerPlade", textBox8.Text);
cmd.Parameters.AddWithValue("#KMKørt", textBox6.Text);
cmd.Parameters.AddWithValue("#dato", textBox7.Text);
cmd.ExecuteNonQuery();
Connection.Close();
button4_Click(sender, e);
}
private void button4_Click(object sender, EventArgs e)
{
/// Connect / Update
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Data", Connection);
DataTable data = new DataTable();
sqlDa.Fill(data);
dataGridView1.DataSource = data;
}
buttonConn.Hide();
}

Updating Data GridView using the selected value inside the dropdown list

I have a dropdownlist and a gridview.. Dropdown list contains the list of the tables I have in my database. What I want is, when I select a particular table name from the dropdownlist, I want all the columns and data inside that particular table display inside the gridview.
This is my code...
Code for displaying the list of tables inside the dropdown is success.. But to bind the columns and data inside the gridview is not success..
Please Help me...
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT table_name FROM INFORMATION_SCHEMA.TABLES", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "table_name";
DropDownList1.DataValueField = "table_name";
DropDownList1.DataBind();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.columns where table_name='+ DropDownList1.selecteditem.text +'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
//+DropDownList1.selecteditem.text +
GridView1.DataBind();
con.Close();
}
}
This is a bad idea on several levels. First you are wide open to SQL injection. Second, you are giving everyone full view access to every column and row of every table.
But the reason you are not getting data is because the select string does not make sense. It should look like this
"SELECT * FROM INFORMATION_SCHEMA.columns where table_name='" + DropDownList1.SelectedValue + "'"
But this is how a proper sql connection should look like.
//create a new datatable
DataTable dt = new DataTable();
//create the string that hold the query including token
string query = "SELECT * FROM INFORMATION_SCHEMA.columns where table_name = #TableName";
//create a new database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.Text;
//replace the token with the correct value
command.Parameters.Add("#TableName", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
//open the connection
connection.Open();
//load the data of the select into the datatable
dt.Load(command.ExecuteReader());
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//but you can also skip the datatable and bind directly to the gridview
GridView1.DataSource = command.ExecuteReader();
GridView1.DataBind();
}

cascading comboBox in windows form using c#

I am trying to Fill Combobox2 on combobox1 selectedText changed from the same table in windows form application. I am using sql serevr 2008 database. I am unable to fill combobox2 on combobox selected text changed.
Here is what i have tried:
private void Purchase_Load(object sender, EventArgs e)
{
fillName();
comboBoxName.SelectedIndex = -1;
}
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxName.SelectedText != "")
{
fillMake();
}
}
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
private void fillMake()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Make from Item Where Item_Name='" + comboBoxName.SelectedText + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Make";
comboBoxName.ValueMember = "Item_Name";
comboBoxName.SelectedIndex = -1;
comboBoxName.Text = "Select";
}
Sql server table for Items
Item_Code Item_Name Item_Make Item_Price UnitofMeasurement
Cable anchor 45.0000 meter
Cable polycab 30.0000 meter
Button anchor 15.0000 unit
Button havells 20.0000 unit
Switch cona 70.0000 unit
I have searched for solution but was unfortunate.
please help me out.
Thanks in advance.
It's a little difficult to figure out what you're trying to do, but it sounds like you are trying to populate a second combo box (comboBoxMake?) depending on what is selected in comboBoxName. I am basing this answer on that assumption. Apologies if I have this wrong.
There are lot of things that need attention in this code. Let's look at fillName() first.
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
You need to Dispose() your database objects. This can be accomplished pretty cleanly with using { .. } blocks.
You don't need to manually open the connection; filling the table with the data adapter
does this automatically.
You don't need the call to ExecuteNonQuery().
You should use the SqlDataAdapter constructor overload that takes a command object, since you have already manually created the command.
Finally, based on my assumption of your goal I have added a distinct to your query so it only gets the unique Item_Names.
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";
}
}
}
}
On to fillMake(). The same suggestions apply that I noted above. Additionally:
Parameterize your SQL. Parameterize your SQL. Not only is this far, far safer than concatenating your SQL together, it is much cleaner. Seriously, read about SQL injection: http://en.wikipedia.org/wiki/SQL_injection
The fillMake() method in your original post seems to be repopulating comboBoxName. Is this correct? You mention two combo boxes but your code only references one. I am assuming you mean to populate another combo box (comboBoxMake?) here:
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.DisplayMember = "Item_Make";
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.SelectedIndex = -1;
comboBoxMake.Text = "Select";
}
}
}
}
Lastly, change the code in the event handler so it looks at the Text rather than the SelectedText property:
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text)) // Text instead of SelectedText
{
fillMake();
}
}

A form is loaded but how to extract data from SQL to combobox?

Still learning C#
A comboBox is created and Tables called mainCat and subCat is created.
I have a code , but i am stuck to understand on how to get the data from mainCat to the comboBox , which is then used by another comboBox for the subCat to set a subcategory.
The Get Connection is underlined red. Why?
Here is my code -
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
SqlCommand cmd = new SqlCommand("SELECT * from MAINCAT");
DataTable dt = new DataTable();
da.Fill(dt);
mainCatU.DataSource = dt;
mainCatU.DisplayMember = "Category";
mainCatU.ValueMember = "Id";
mainCatU.Text = "<-Please select Category->";
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
So i then i tried another code.. but still doesnt work..
public partial class User : Form
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Integrated Security=True";
con.Open();
MessageBox.Show("Database connected");
ds1 = new DataSet();
string sql = "SELECT * from MAINCAT";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "SCSID");
mainCatU.DataSource = ds1;
con.Close();
mainCatU.Text = "<-Please select Category->";
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
}
}
then i just used the data bound item function through the combobox GUI..
this.mAINCATTableAdapter.Fill(this.masterDataSet.MAINCAT);
but , the box didn't show any value , except "System.Data.DataRowView" in the comboBox
==================================================================================
System.Data.SqlServerCe.SqlCeConnection con; //not used at the moment
System.Data.SqlServerCe.SqlCeDataAdapter da; //not used at the moment
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
MessageBox.Show("Database connected");
SqlDataAdapter da = new SqlDataAdapter("SELECT * from MAINCAT", conn);
ds1 = new DataSet();
da.Fill(ds1, "MainCat");
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
}
===============
and the combo box is still not showing anything from the database table
You need to create the function GetConnection():
public string ConnectionString { get; set;}
public SqlConnection GetConnection()
{
SqlConnection cn = new SqlConnection(ConnectionString);
return cn;
}
TBH, unless you want to do something in GetConnection, you might be better just creating it inline:
using (SqlConnection Con = new SqlConnection(ConnectionString))
{
EDIT:
Based on your revised question, I think the problem now may be here:
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
My guess is that your table structure is not maincat.maincat. The display and value members should be set to the field name that you wish to display.
I am really sorry I am a vb developer but the concept is same to populate data into combo using sql is
Declare SQLConnection Declare SQLDataReader Declare SQLCommand
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.

Categories