How to make it work? C# GridView Delete Line - c#

protected void gv_pedidos_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int idPedido = Convert.ToInt32(gv_pedidos.DataKeys[e.RowIndex].Values["idPedido"].ToString());
SqlConnection con = new SqlConnection(#"Server=localhost\SQLEXPRESS;Database=Kirchesch;Trusted_Connection=True;");
SqlCommand com = new SqlCommand(#"DELETE FROM pedidosFeitos WHERE idPedido = #idPedido", con);
com.Parameters.AddWithValue("#idPedido", idPedido);
con.Open();
com.ExecuteNonQuery();
con.Close();
preencheGrid();
}
This is the back-end of my code, the error I'm getting is on the variable idPedido, the third line.

Just use Convert.ToInt32(e.RowIndex);
The datakey is selected for the operation from the selected row index

You can get idPedido like this in RowDeleting event:
int idPedido = int.Parse(gv_pedidos.Rows[e.RowIndex].FindControl("idPedido").toString());

Related

Using SAME Textbox to search and insert data in dataGridView

I have a Textbox with which I want to be able to Search and Insert data into Table. Insert works fine with one exception: When I try to Insert data that isn't already in DB(it's searching while I'm typing) it gives me:
"Exception User-Unhandled System.NullReferenceException: 'Object
reference not set to an instance of an object.'
System.Windows.Forms.DataGridView.CurrentRow.get returned null.
I think I'm missing something in the Search code.
//UPDATE: All of the code.// This is my Insert and Search code:
namespace UDDKT
{
public partial class FrmGlavna : Form
{
DataSet ds = new DataSet();
SqlDataAdapter DaDavaoci = new SqlDataAdapter();
SqlDataAdapter DaAkcije = new SqlDataAdapter();
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
public FrmGlavna()
{
InitializeComponent();
}
//Popunjava DataGridViews sa podacima iz baze
private void FrmGlavna_Load(object sender, EventArgs e)
{
SqlCommand SlctDavaoci = new SqlCommand("SELECT * FROM Davaoci ORDER BY DavaocID DESC", cs);
DaDavaoci.SelectCommand = SlctDavaoci;
DaDavaoci.Fill(ds, "TblDavaoci");
SqlCommand SlctAkcije = new SqlCommand("SELECT * FROM AkcijaDDK", cs);
DaAkcije.SelectCommand = SlctAkcije;
DaAkcije.Fill(ds, "TblAkcije");
DgDavaoci.DataSource = ds.Tables["TblDavaoci"];
}
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
//Osvježava DataGridView nakon unosa/izmjene/brisanja podataka u bazu
private void RefreshTable()
{
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
String query = "SELECT * FROM Davaoci ORDER BY DavaocID DESC";
SqlCommand cmd = new SqlCommand(query, cs);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DgDavaoci.DataSource = dt;
}
//Čisti TextBox nakon upisa/izmjene/brisanja podataka u bazu
public void ClearTxtBx()
{
TxtIme.Clear();
TxtPrezime.Clear();
TxtTezina.Clear();
TxtAdresa.Clear();
TxtBrojTel.Clear();
TxtBrojLK.Clear();
}
//Upis podataka u Tabelu Davaoci
private void BtnDodajDavaoca_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Davaoci (Ime,Prezime,Pol,DatumRodjenja,KrvnaGrupa,Tezina,Adresa,BrojTel,BrojLK) VALUES (#Ime, #Prezime, #Pol, #DatumRodjenja, #KrvnaGrupa, #Tezina, #Adresa, #BrojTel, #BrojLK)";
using (SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True"))
using (SqlCommand command = new SqlCommand(query, cs))
{
command.Parameters.Add("#Ime", SqlDbType.NVarChar).Value = TxtIme.Text;
command.Parameters.Add("#Prezime", SqlDbType.NVarChar).Value = TxtPrezime.Text;
command.Parameters.Add("#Pol", SqlDbType.NChar).Value = TxtPol.Text;
command.Parameters.Add("#DatumRodjenja", SqlDbType.Date).Value = TxtDatumRodjenja.Text;
command.Parameters.Add("#KrvnaGrupa", SqlDbType.VarChar).Value = TxtKrvnaGrupa.Text;
command.Parameters.Add("#Tezina", SqlDbType.Float).Value = TxtTezina.Text;
command.Parameters.Add("#Adresa", SqlDbType.NVarChar).Value = TxtAdresa.Text;
command.Parameters.Add("#BrojTel", SqlDbType.NVarChar).Value = TxtBrojTel.Text;
command.Parameters.Add("#BrojLK", SqlDbType.NVarChar).Value = TxtBrojLK.Text;
cs.Open();
command.ExecuteNonQuery();
cs.Close();
RefreshTable();
ClearTxtBx();
}
}
//Pretraga postojećih Davalaca
private void TxtIme_TextChanged(object sender, EventArgs e)
{
(DgDavaoci.DataSource as DataTable).DefaultView.RowFilter = string.Format("Ime LIKE '{0}%'", TxtIme.Text);
}
}
}
}
Here is the MockUp of the Form before I begin to type/search/insert Data that isn't already in the Table (First Textbox*).
And after I start typing Name(Име) that starts with an "A" (name that isn't already in the Table).
I want to Search DB for that Column, but if there aren't any existing names, I want to be able to continue typing (without interuption) so that I can Insert new data into table.
DgDavaoci.CurrentRow in your DgDavaoci_SelectionChanged method is null, so attempting to access DgDavaoci.CurrentRow.Cells["DavaocID"] throws the NullReferenceException. The reason, best I can tell, is as follows:
You begin to type a value into your text box, a value that happens not to be found in the data set. As you type, you cause the TxtIme_TextChanged method to execute. It filters according to your search, and since the value is not found, it filters out every row in the set. Here's the important part: whenever the data set is filtered, it has the possibility of causing DgDavaoci_SelectionChanged to execute. Since the selection changed from the first row to no row at all (since there are no filtered rows to display), this method does execute. Now, when the method attempts to access the current row, there is no current row, and so we get a null here. Attempting to access a field of null throws the exception you're getting.
How can you fix this behavior? A simple null-check in DgDavaoci_SelectionChanged should do the trick. It looks to me like you can simply return from that method if(DgDavaoci.CurrentRow == null), or you can code in additional behavior. Just perform a check so that you don't reference the null object.
Probably the filter inside TxtIme_TextChanged is causing the DataGridView's SelectionChanged event to fire and the code is entering DgDavaoci_SelectionChanged. The exception indicates that DgDavaoci.CurrentRow is null, so you'll need to handle the case where DgDavaoci.CurrentRow is null in DgDavaoci_SelectionChanged.
A simple way to deal with this would be to just check DgDavaoci.CurrentRow is null and return from the function if that evaluates to true.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
It looks like you might have a second DataGridView (DgAkcije) that is designed to show the details of the currently selected row in DgDavaoci. So, another approach might be to just clear DgAkcije if DgDavaoci.CurrentRow is null.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
DgAkcije.DataSource = null; //I'm not 100% sure this will work, I haven't tested it.
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
Ultimately, however, you'll have to decide what you want to happen when DgDavaoci_SelectionChanged is called but DgDavaoci.CurrentRow is null.
Solution if anyone else is interested:
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow != null)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
}

how to avoid two empty rows at single click in gridview

I have a grid view. If I click the add button, an empty row is created. There is more than one empty row in the grid view. Now if I click the delete button on the selected row, all the empty rows are deleted. I want to delete the selected empty row only.
thank you..please help ..
delete code is here...
protected void gvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gvEmployeeDetails.Rows[e.RowIndex].FindControl("lblEmpID");
conn.Open();
string cmdstr = "delete from EmployeeDetails where empid=#empid";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", lblEmpID.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
add row code here.........
in add row i want alert message if the name textbox is empty
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(empid,name,designation,city,country) values(#empid,#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#empid", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", txtAddDesignation.Text);
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
Can you change the "empid" column to be Identity? This is done from SQL management studio and will make your column to be unique and will auto increment the values in it. After that you will remove it from the Add method and the SQL will take care of it. This will fix your problem.
In SQL you must go the the EmployeeDetails table. Choose design from your options and then go the to empid column. On it you can open Column Properties and expand the "Identity Specifications". Then change "(Is Idetity)" to "Yes" and save the table. See the screenshot below:
Then your Add code should look like that:
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddName = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddName");
if(string.IsNullOrEmpty(txtAddName.Text))
{
MessageBox.Show("Name is empty"); // or some logging, you decide
}
else
{
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
TextBox txtAddCity = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCity");
TextBox txtAddCountry = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddCountry");
conn.Open();
string cmdstr = "insert into EmployeeDetails(name,designation,city,country) values(#name,#designation,#city,#country)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#name", txtAddName.Text);
cmd.Parameters.AddWithValue("#designation", txtAddDesignation.Text);
cmd.Parameters.AddWithValue("#city", txtAddCity.Text);
cmd.Parameters.AddWithValue("#country", txtAddCountry.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
}
also try this one also,
gvEmployeeDetails.DeleteRow(Row name/index);
try this code:
gvEmployeeDetails.AllowUserToAddRows = false;
It will Automatically delete Empty row.

ArguementOutOfRangeException was unhandled error

i'm very new to programming and c#. here i'm having ArguementOutOfRangeException. i want to add a new data row to the datagridview every time when click the button. so i used a variable "i" to increase the value one by one and change the row value when i use "0" which means
dataGridView2.Rows[0].Cells[0].Value = textBox1.Text.ToString();
instead of "i" the first row fills but when use "1" which means
dataGridView2.Rows[1].Cells[0].Value = textBox1.Text.ToString();
the exception comes. what is the right way to do such a thing ?
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public SqlConnection conn;
public int i = 0;
private void Form2_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Data Source=.\\SQLEXPRESS; Integrated Security=sspi; Initial Catalog=student");
conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
string Sqlstr = "insert into student(name, pw)values(#name,#pw)";
SqlCommand cmd = new SqlCommand(Sqlstr, conn);
cmd.Parameters.AddWithValue("#name", textBox1.Text);
cmd.Parameters.AddWithValue("#pw", textBox2.Text);
if (cmd.ExecuteNonQuery() > 0)
{
i++;
DataGridView dataGridView1 = new DataGridView();
dataGridView2.Rows[i].Cells[0].Value = textBox1.Text.ToString();
dataGridView2.Rows[i].Cells[1].Value = textBox2.Text.ToString();
}
label1.Text = Convert.ToString(i);
}
}
}
You don't have to define a new DataGridView each time on a button click, I believe you want to add a new row in your existing DataGridView after the insert in database. You can do:
if (cmd.ExecuteNonQuery() > 0)
{
DataGridViewRow row = (DataGridViewRow)dataGridView2.Rows[0].Clone();
row.Cells[0].Value = textBox1.Text.ToString();
row.Cells[1].Value = textBox2.Text.ToString();
dataGridView2.Rows.Add(row);
}
You have to add new rows before you try writing in them. Use dataGridView2.Rows.Add( something ), check out the Add method.

Unable to get the cell value in rowdeleting event in grid view

I am trying to delete the row in the grid view. For that one i am writing code in the rowdeleting event like below.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string UserId;
SqlTransaction tran;
using (con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["EMASFBAConnectionString"].ConnectionString;
cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
tran = con.BeginTransaction();
TableCell cell = GridView1.Rows[e.RowIndex].Cells[1];
string username = cell.Text;
cmd.Transaction = tran;
cmd.CommandText = "Delete from aspnet_Users where UserName='" + username + "'";
UserId = cmd.ExecuteScalar().ToString();
if (UserId.Length!=0)
{
//delete user from membership table.
errorLabel.Text = "User is ready to delete";
}
tran.Commit();
con.Close();
}
}
when i debug the cell value is coming as empty. What i did the mistake here?
This grid view has edit and delete button in front of the each row.
I tried with Cells[0],Cells[2] but giving the empty values only. Can any one give me the solution?
hi define datakeys in the gridview and use this method
string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString();
and then based on this ID delete the row.
cmd.CommandText = "Delete from aspnet_Users where UserID=" + UserID;
after that call your databind method to bind the gridview with updated records
for datakeynames please use this
<asp:gridview datakeynames="UserID"
runat="server">
Finally got the answer. If i try to get the values as Table cells it is not giving proper values. So i tried like this,
GridViewRow row = GridView1.Rows[e.RowIndex];
Label usernamelable = (Label)row.FindControl("lblUserNameValue");
string username = usernamelable.Text;
This works fine for me. I am referring the label control inside the gridview and getting the value.
try the following code:
var empId = Convert.ToInt32(this.gvDetails.DataKeys[e.RowIndex].Values["EmpId"].ToString());
protected void NPNGridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = NPNGridView1.SelectedRow;
TextBox1.Text = gvr.Cells[1].Text;
}
it's working, before u run the solution, please once test this Cells[1] indexes,

Datagrid refresh not working

I have a datagrid to display some information from a SQL table, and then a simple textbox and button to allow users to add records to the database. Problem is, when the user clicks Add, the datagrid SHOULD update, but it doesn't, any ideas? The code in question is as follows:
protected void Page_Load(object sender, EventArgs e)
{
username.Text = Session["username"].ToString();
datetime.Text = DateTime.Now.ToString();
BindData();
}
protected void BindData()
{
string SQLQuery = "SELECT * From Filters";
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
DataSet resultsDataSet = new DataSet();
MyConn.Open();
OleDbDataAdapter DataAdapter = new OleDbDataAdapter(SQLQuery, MyConn);
DataAdapter.Fill(resultsDataSet);
DGFilters.DataSource = resultsDataSet;
DGFilters.DataBind();
if (resultsDataSet.Tables[0].Rows.Count == 0)
{
no_records.Visible = true;
DGFilters.Visible = false;
}
else
{
DGFilters.Visible = true;
no_records.Visible = false;
}
MyConn.Close();
}
protected void AddFilter_Click(object sender, EventArgs e)
{
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
MyConn.Open();
string SQLInsert = "INSERT INTO Filters (FilterString) VALUES ( '" + FilterToAdd.Text + "')";
OleDbCommand MyCmd = new OleDbCommand(SQLInsert, MyConn);
MyCmd.ExecuteNonQuery();
MyConn.Close();
DataBind();
}
Any ideas?
At the bottom of your AddFilter_Click method you need to call your own BindData() so the grid can be refreshed with the new record. Right now you're calling DataBind(), which is a method on the base class Control, which is being applied to your entire web form. I'm guessing this isn't doing much of anything.
Also, in your Page_Load method, you can probably change this:
BindData();
to
if (!Page.IsPostBack)
BindData();
so that you don't bind your grid twice when the user clicks on the 'add' button.

Categories

Resources