This is my code:
private void Bind()
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from SuperCars", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand delcmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
delcmd.CommandText = "DELETE FROM SuperCars WHERE Car='%" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";
con.Open();
delcmd.Connection = con;
delcmd.ExecuteNonQuery();
con.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
MessageBox.Show("Row Deleted");
}
Bind();
}
I want to put a delete button in my application. When I select a row and click the delete button, it throws the exception below:
Index was out of range. Must be non-negative and less than the size of the collection.
The problem is you don't know how to select a row as well as how the DataGridView understands when a row is called selected. To select a row, you have to click on the row header, or if you want to select the row just by clicking on any cell on the row, just set the property SelectionMode to DataGridViewSelectionMode.FullRowSelect. Then the SelectedRows should have at least 1 item, the index out of range exception should not be thrown any more.
If you intend to allow user to delete 1 row at a time, I think you can use the property CurrentRow to get the current selected row, you can also use the CurrentCell or CurrentCellAddress and derive the selected row from them.
Please display the code in side Bind() function. I think record was not removed in the database and when you call Bind() function at that time record again bind in the gridview.
I think your delete query is wrong , if you want to remove record which have car as cell[0] value so query will be as below :
delcmd.CommandText = "DELETE FROM SuperCars WHERE Car Like '%" +dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";
Related
I'm unsure what happened. But it is affecting all my tables. Just a few hours ago when a page/form loads my datagrid view would show all the data in the table at once. Now everything is blank/white unless I click my mouse on the cell and it highlights the whole row but still does not show the other rows unless I click on the cells.
First cell selected, shows the whole row
Second row shows but first row is now hidden
How do I fix this? Everything was fine a few hours ago. I didn't even make any changes to my datagridview and now their all affected.
private void Add_Products_Load(object sender, EventArgs e) {
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
displayproduct_info();
fill_combobox();
}
public void displayproduct_info() {
//comboBox1.Items.Clear();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Product_listing";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
I have a gridview on my page. And I have 2 snippets of SQL code to binds that gridview.
First one is run on page load. If there are records returned from the first SQL, I can select a row on gridview.
But the problem is when there is no record returned from the first SQL, I have button that runs another SQL and binds its result to the gridview too. But when I try to select a row, I get this error:
Index was out of range. when I trying to select a row Must be non-negative and less than the size of the collection. Parameter name: index
My code is like that
First SQL (its run on page load)
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and thats the second SQL that when runs when I click button
void listelehepsi()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and this is the GridView1_SelectedIndexChanged event
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int secili;
secili = GridView1.SelectedIndex;
GridViewRow row = GridView1.Rows[secili]; // I GOT ERROR HERE
TextBox1.Text = row.Cells[1].Text;
}
why Am I getting this error ?
EDIT--
I got solve changing the page load sql like this;
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
if (!IsPostBack)
{
GridView1.DataBind();
}
else
{
//
}
baglanti.Close();
}
Make sure that you are not rebinding your datagrid on postback - you can do this in your PageLoad event - something like
if (!IsPostback)
{
... bind your datagrid
}
In the GridView1_SelectedIndexChanged event, could you simply do a RowCount to see if the value is != 0 before the other code runs?
if (GridView1.RowCount <= 0)
{
return;
}
I want to know how to populate a DataGridView with information found from a Select statement. Here's my event for the select button:
private void SelectCust(object sender, EventArgs e)
{
OleDbConnection conn = null;
conn = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + "c:/inetpub/ftproot/ora103/App_Data/Fashion.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from Customer where CustNum = #MyCust ", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
if (dt.Rows.Count > 0)
{
}
conn.Close();
}
I want to use the "if" statement to insert information I've gathered from my Customers table, and populate a DataGridView. However, I'm having trouble connecting the DataGridView to my Microsoft Access Database (called Fashion.accdb). Here's what my DataGridView looks like as of now (I know it's not much):
<asp:GridView ID="dataGridView1" runat="server" EnableModelValidation="True">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
EDIT
Here's the error :
Exception Details: System.Data.OleDb.OleDbException: No value given
for one or more required parameters.
The idea is that I'll be typing in a customer number into a textbox. Then I'll hit the submit button. Then the event will retrieve that number from the textbox that was typed in, grab the information in the database pertaining to that customer, and display it in a GridView
oledb parameters are different than sql server's.
...where CustNum = #MyCust
needs to be
...where CustNum = ? (or: where CustNum = [?])
after setting the adapter's command, set the parameter(s):
cmd.Parameters.Add("#CustNum", OleDbType.Integer, 15).Value = yourValue;
hope that helps.
using query i have called two columns value from database into one column. the point is now i want to select a value form combobox and put one column value into textbox.
e.g
two column values from database into combobox below
10001 haider <------ when i select this index i want only haider to be viewed into the textbox
10002 fahad
10003 aitazaz
the snippet which i have used for calling the two colums value from database is:
public void account()
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no, acc_name FROM accounts_record";
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbacc.Items.Add(ds.Tables[0].Rows[i][0] + " " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
You should be adding values and text to the combobox separately.
Here's an example ComboBox: Adding Text and Value to an Item (no Binding Source).
If you have to display the id in the text you have to do some parsing before putting the selected text into the textbox.
Use ComboBox.SelectedIndexChanged event of the combobox to populate the textbox accordingly. use http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged(v=vs.110).aspx
If you are able to get the 2 value text of the combo box on selection change then you can split it with space (" ") character and take the 2nd string and put it in textbox.
For example
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitedStr = comboBox1.SelectedText.Split(' ');
textBox1.Text = splitedStr[1];
}
You should use the code as below
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no +'-' + acc_name as AccNoWithName , acc_no as ActNo FROM accounts_record";
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dsn = new DataSet();
adpt.Fill(dsn);
con.Close();
comboBox1.DisplayMember = "AccNoWithName";
comboBox1.ValueMember = "ActNo";
comboBox1.DataSource = dsn.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedValue.ToString();
}
In C# I used a combo box in my form and I wish to obtain a specific column from a table in the database and contents of the column to be added as the items in the combo box.
I have declared this way
string strCon, strQry;
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
SqlCommand comm;
den strcon= data source =" " initial catalog =" " use id =" " password=" ";
con = new sqlconnection(strcon);
strquery = select city from the cities;
da = new sqladapter(strqry,con);
ds = new dataset;
da.fill(ds, " cities");
Should I put for loop till items continue adding?
Update:
I want the entire column to be added as the items in the check box. On click of the check box, I want the entire column to be displayed as respective item in the check box.
comboBox1.Items.Add(drCities.Cells[0].Value);
comboBox1.Items.Add(drCities.Cells[1].Value);
Try this: if you want to display one column called 'Name' then...
comboBox1.DataSource = ds;
comboBox1.DisplayMember = "Name";
else, as you have described, you might want to do this...
foreach(DataRow drCities in ds.Tables[0].Rows)
{
string sValue = string.Format("{0} {1} {2}", drCity["Name"], drCity["Col1"], drCity["Col2"]);
comboBox1.Items.Add(sValue);
}
the above code would sit in the Form load event which is usually...
private void Form1_Load(object sender, EventArgs e)
{
....
}