All Row has a Delete Button in Gridview - c#

I have a simple page like this. (EKLE = ADD, SİL = DELETE)
And my AVUKAT Table like this.
Simplify, When i choose first dropdown MUSTERI and second dropdown AVUKAT , add the database (getting HESAP (number) automaticly) or delete the database and gridview.
This is my code.
ADD Click
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
/*GridView1.DataSource = dr;
GridView1.Visible = true;*/
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
DELETE Click
protected void Delete_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("DELETE FROM AVUKAT WHERE MUSTERI = #MUSTERI AND AVUKAT = #AVUKAT AND HESAP = #HESAP", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
/* GridView1.DataSource = dr;
GridView1.Visible = true;*/
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
My manager wants, delete process is so hard. Let's make easy. Because when i want to delete some data, i must choose two dropdownlist and then delete(Sil) button.
We should prefer that every row has a delete button. Then when we click the button. Then must be deleted gridview AND databse.
I found perfect example on the internet abuot what i want.
I think if we can do that, Sil(Delete) Button should be deleted.
How can we do that?
I think AutoDeleteButton don't work like this. Right? It just deleted from Gridview. Not Database. But i want deleting both (Gridview AND Database)

You need to ensure you calling the correct method.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview_events.aspx
Clicking the button will run the "RowDeleting" method then "RowDeleted".
Edit - forgot to mention, once you've run your deleted method you'll need to rebind the gridview.
GridView1.DataBind()

Related

delete gridview linkedbutton

I'm trying to delete the row in gridview when the user is click delete linked button, the code is work correctly but in user interface the gridview is disappearing completely. How can I fix the disappearing gridview ?
I want only the row that actually deleted is disappear not the whole gridview ?
here is my code
void PopulateGridview()
{
DataTable dtble = new DataTable();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("select v.visitor_Fname,v.visitor_Mname,v.visitor_family_name,v.visitor_mobile,v.visitor_table_id,v.place_of_work,v.country_name from visitor v join requests r on r.request_id =v.request_id where r.request_id =(select MAX(request_id) from requests where user_id='" + (int)Session["empNo"] + "' )", con);
adapt.Fill(dtble);
}
if (dtble.Rows.Count > 0)
{
GridView2.DataSource = dtble;
GridView2.DataBind();
}
else
{
dtble.Rows.Add(dtble.NewRow());
GridView2.DataSource = dtble;
GridView2.DataBind();
GridView2.Rows[0].Cells.Clear();
GridView2.Rows[0].Cells.Add(new TableCell());
GridView2.Rows[0].Cells[0].ColumnSpan = dtble.Columns.Count;
GridView2.Rows[0].Cells[0].Text = " بيانات الزائر";
GridView2.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
SqlConnection con2 = new SqlConnection(conString);
con2.Open();
String a = "Insert into dbo.visitor(visitor_Fname,visitor_Mname,visitor_family_name,visitor_mobile,place_of_work,country_name, request_id)values(#FName,#MName,#FamilyName,#Mobile,#work,#country,'" + Last_request_id.ToString() + "')";
SqlCommand cmd2 = new SqlCommand(a, con2);
cmd2.Parameters.AddWithValue("#FName", (GridView2.FooterRow.FindControl("FirstNameFooter") as TextBox).Text.Trim());
cmd2.Parameters.AddWithValue("#MName", (GridView2.FooterRow.FindControl("MNameFooter") as TextBox).Text.Trim());
cmd2.Parameters.AddWithValue("#FamilyName", (GridView2.FooterRow.FindControl("FamilyNameFooter") as TextBox).Text.Trim());
cmd2.Parameters.AddWithValue("#Mobile", (GridView2.FooterRow.FindControl("visitorMobileFooter") as TextBox).Text.Trim());
cmd2.Parameters.AddWithValue("#work", (GridView2.FooterRow.FindControl("place_of_workFooter") as TextBox).Text.Trim());
cmd2.Parameters.AddWithValue("#country", (GridView2.FooterRow.FindControl("country") as DropDownList).SelectedValue.Trim());
cmd2.ExecuteNonQuery();
PopulateGridview();
}
con2.Close();
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
SqlConnection con2 = new SqlConnection(conString);
con2.Open();
LinkButton butt = (LinkButton)sender;
int ID = Convert.ToInt32(butt.CommandArgument.ToString());
string del = "delete from visitor where visitor_table_id =#ID";
SqlCommand cmd2 = new SqlCommand(del, con2);
cmd2.Parameters.AddWithValue("#ID", ID);
cmd2.ExecuteNonQuery();
GridView2.DataBind();
con2.Close();
}
I think you should try to repopulated the DataGrid's DataSource property again, after you execute the delete command. meaning, try swapping:
GridView2.DataBind(); in LinkButton2_Click to a call to:
PopulateGridview()
Hope it helps!
You have to load your DataSource in click event again. Than call DataBind().

C# check userid already exists

I am designing a web form to insert data into sql database.I just want to check that email id which is unique already exists or not.
code:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox2.Text))
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("select shop_email from shop where shop_email=#email", con);
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Label1.Text = "email id already exists";
}
con.Close();
}
}
I tried above code but its not working i.e Label is not displaying anything.Any help will be thankful.
Problem : You are writing your code in TextBox_TextChanged Event handler so it would be invoked for everytime whenever there is a change in the TextBox and it would not give you the result untill unless you enter the complete Email-ID.
Solution 1: You need to write the above code in some Button Click Event handler as below:
protected void btnSearch_Click(object sender,EventArgs e)
{
//Write your code here
}
Solution 2: if you want to keep your code in the TextBox TextChanged Event handler but still want to identify the EmailID you can use LIKE operator instead of = operator
Try This:
SqlCommand cmd = new SqlCommand("select shop_email from shop
where shop_email LIKE #email", con);
cmd.Parameters.AddWithValue("#email", "'%"+TextBox2.Text +"%'"+);
try to add else statement in case if user/email does not exist
Also move this code to button click event or some other event. On Text Box text change event it will not return result.
using (var con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True"))
using(var cmd = new SqlCommand("select 1 from shop where UserID=#UserID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserID", TextBox2.Text);
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
Label1.Text = "userid already exists";
}
else
{
Label1.Text = "userid doesn't exists";
//Create new user
}
}
}

id getting inserted without selecting in c#.net

private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
In the first class i have a combobox and i am fetching its value from database and i have shown "Select Project Name" on page load in combobox.I want to insert its value only when user selects option from dropdown and insert nothing if user did not choose any option.
Now the problem is that the first name in the dropdown gets inserted on button click.without choosing any option.I want that if user did not choose any name value from dropdown nothing should get inserted.
can anyone help me..?
Assuming that datatype of ID column is int:
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
//begin adding line
DataRow row = table.NewRow();
row["project_name"] = "Select Project Name";
row["ID"] = 0;
table.Rows.InsertAt(row, 0);
//end adding line
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
if(combo_status.SelectedValue == 0)
{
return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
}
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Hope this will help you

Click Button - No Action

I am trying to retrieve information from database. User enters id of the person he is looking for to ID textbox, than press display button. The grid view should show the result. But when button is pressed, nothing happens. Could anyone help or tell me what I should check?
Code for button:
protected void btnDisplay_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
SqlCommand cmd = new SqlCommand("displayData", conn);
conn.Open();
cmd.Parameters.Add("#ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rd = cmd.ExecuteReader();
grvResults.DataSource = rd;
grvResults.DataBind();
}
Here is stored procedure:
USE ["Name"]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[displayData] (#ID int)
as
begin
SELECT * FROM Customers WHERE ID = #ID
end
Here is display data method:
public List<Customer> displayData()
{
List<Customer> lst = new List<Customer>();
SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * From Customers", conn);
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
lst.Add(new Customer()
{
ID = rd.GetInt32(0),
FName = rd.GetString(1),
LName = rd.GetString(2)
});
}
return lst;
}
aspx for button:
<asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" />
have you tried to put a breakpoint in button click. Is it hitting breakpoint. If not then I will say remove
OnClick="btnDisplay_Click"
from your aspx page. And then add default click event from .cs page by selecting control and it events. Them try to debug line by line.
Give the following code a try in your codebehind. It should bind properly and fill a gridview. If it works, add more code from there. If it doesn't work, look at things like your connection string. Let me know.
SqlConnection conn = new SqlConnection("Data Source="?";Initial Catalog="?";Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers WHERE ID = #ID", conn);
cmd.Parameters.Add("#ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
conn.Close();
grvResults.DataSource = dt;
grvResults.DataBind();
I think you are complicating yourself too much
First do this:
That should make it work. You already have a stored procedure which makes it easier. (Sorry for the pictures, I wanted to make sure you understood this)

Reload Items of dataGridView

I have a dataGridView in C# WinForms that display a custom items from a table in my database, and I have textbox and button for insert new rows in that table.
When I click on button, the Text of textbox will be inserted into table, I want after inserting, dataGridview can reload new item and display it too.
I use dataGridView1.Update(); and dataGridView1.Refresh(); and don't work.
I know that dataGridView can insert new items, but I want to insert items in my way.
it's my code on click event:
private void button1_Click(object sender, EventArgs e)
{
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\bank.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
String cmdText = "insert into marja (ayatollah) values(#n)";
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#n", textBox4.Text);
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
dataGridView1.DataSource = marjaBindingSource;
textBox4.Text = "آیت الله ";
}
else
MessageBox.Show("Error");
conn.Close();
}
You should try databinding, and possibly populate your data into ObservableCollection, you don't need manually call update, all is done automatically.
See also this post: Reloading Listbox content
Well you will have to use DataBind method to reload the datagridview.
Lets say DataGridView1 is the ID of your datagridview then use the below line of code after your Insert statement.
DataGridView1.DataSource = yourDataSource;
Refresh and Update methods wont server your purpose here.
All read this link for more information.
Can you alter your code to this:
private void button1_Click(object sender, EventArgs e)
{
int rowsAffected = 0;
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\bank.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
String cmdText = "insert into marja (ayatollah) values(#n)";
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#n", textBox4.Text);
cmd.Connection = conn;
conn.Open();
rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
if (rowsAffected > 0)
{
dataGridView1.DataSource = marjaBindingSource;
textBox4.Text = "آیت الله ";
}
else
{
MessageBox.Show("Error");
}
}
this.marjaTableAdapter.FillBy(this.bankDataSet10.marja);
it's my answer

Categories