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().
Related
When I'm choosing additional (empty) position on Dropdownlist created by DropDownList.Item.Insert whole application is terminated.
if (!Page.IsPostBack)
{
DropDownList4.Items.Add(new ListItem("", ""));
DropDownList4.AppendDataBoundItems = true;
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
String strQuery = "select * from projects";
OleDbConnection con = new OleDbConnection(strConnString); ;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
string strQuery = "select * from projects where" + " ID = #ID";
OleDbConnection con = new OleDbConnection(strConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.Parameters.AddWithValue("#ID", DropDownList4.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
OleDbDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
myreader.Read();
TextBox12.Text = myreader["Project_name"].ToString();
TextBox2.Text = myreader["Owner"].ToString();
myreader.Close();
}
finally
{
con.Close();
}
}
As I'm thinking the reason is that the empty value does not exist in DB (but it is just created every time on Page_load by DropDownList4.Items.Add(new ListItem("", ""))). How to exclude from checking in DB first empty position on DropDownList?
Edited:
...
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
if (DropDownList4.SelectedItem.Value == null || DropDownList4.SelectedItem == null)
{
}
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
Still does not working
Edited:
string selected = DropDownList4.SelectedItem.Text;
if (string.IsNullOrEmpty(selected))
{
}
Now - It's working :)
You need (and want to) add the blank dropdown row AFTER you fill the dropdown.
So, say we have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
And I DO suggest that you put the DataValue/Text settings in the control - really no need or advantage to putting that code in code behind.
And we don't need (or want) to re-load or re-insert the extra blank dropdown choice each time - so load the dropdown ONLY one time (the PostBack = false in page load as you attempted is correct).
So, we will select a hotel, and then pull that ONE database row for additional information - shove into a few text boxes as your code example does.
I suggest this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotels ORDER BY HotelName";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
DataTable MyRstP(OleDbCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string HotelPK = DropDownList1.SelectedItem.Value as string;
string strSQL = "SELECT * FROM tblHotels where ID = #ID";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = HotelPK;
DataTable rstData = MyRstP(cmdSQL);
if (rstData.Rows.Count > 0)
{
DataRow OneRow = rstData.Rows[0];
TextBox1.Text = OneRow["HotelName"].ToString();
txtTaxRate.Text = OneRow["HotelTax"].ToString();
}
}
We also assume and have AutoPostBack = true for the drop list to fire each time we change it.
I can use these UpdateQuery on WinForms, now I convert it to ASP.NET Version and use this UpdateQuery again and not work. Others SELECT, INSERT, DELETE all works well, only update, also no error have given.
protected void updateBtn_Click(object sender, EventArgs e) {
DataTable dt = new DataTable();
string sql = "UPDATE patient SET ID=?ID, NameCH=?NameCH, NameEn=?NameEn, NRIC=?IC, Tel=?Tel, Email=?Email, Sex=?Sex, Occupation=?Occupation, Married=?Married, Address=?Address, Allergies=?Allergies, LTM=?LTM, MH=?MH, Other=?Other WHERE ( 'ID'=?ID )";
MySqlConnection con = new MySqlConnection(conStr);
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.Parameters.AddWithValue("?ID", ids.Text);
cmd.Parameters.AddWithValue("?NameCH", CHName.Text);
cmd.Parameters.AddWithValue("?NameEN", ENName.Text);
cmd.Parameters.AddWithValue("?IC", NRIC.Text);
cmd.Parameters.AddWithValue("?Tel", TEL.Text);
cmd.Parameters.AddWithValue("?Email", Email.Text);
cmd.Parameters.AddWithValue("?Sex", sex.Text);
cmd.Parameters.AddWithValue("?Occupation", occupation.Text);
if (married.Checked) {
cmd.Parameters.AddWithValue("?Married", "YES");
} else {
cmd.Parameters.AddWithValue("?Married", "NO");
}
cmd.Parameters.AddWithValue("?Address", address.Text);
cmd.Parameters.AddWithValue("?Allergies", Allergies.Text);
cmd.Parameters.AddWithValue("?LTM", ltm.Text);
cmd.Parameters.AddWithValue("?MH", medicalhis.Text);
cmd.Parameters.AddWithValue("?Other", record.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/Pages/Home.aspx/Update");
}
I have a tabcontrol, it has 9 tabpage collection each tabpage has a datagridview and a searchbox.
private void txtsrchesd_TextChanged(object sender, EventArgs e)
{
if (txtsrchesd.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM esd_view where department like '" + txtsrchesd.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgesd.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
private void txtsrchope_TextChanged(object sender, EventArgs e)
{
if (txtsrchope.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view where department like '" + txtsrchope.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
The output of the other datagridview appears on the other datagridview , how can I clear the output of the datagridview as I clear what I type on my searchbox
hope you understand , thank you for the help
When you are checking with:
{
if (txtsrchope.Text != "")
{}
.....
}
In the else part you don't need to fire the same query as when:
txtsrchop.text ==""
You can replace your else part by this code:
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
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
Hello sir i wanna search the data using checkbox aur checkboxlist like if i select two checkbox then i wanna to get the data of both the checkbox id's this code is giving me only one data at a time. please give me a demo code for this type of query.
private void checkboxlistbind()
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\FlagBits\\Documents\\Visual Studio 2010\\WebSites\\checkboxlist\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True");
con.Open();
string query = "select * from student where id='" + CheckBox1.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
private void checkboxlistbind2()
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\FlagBits\\Documents\\Visual Studio 2010\\WebSites\\checkboxlist\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True");
con.Open();
string query = "select * from student where id='" + CheckBox2.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
checkboxlistbind();
}
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
checkboxlistbind();
checkboxlistbind2();
}
You need to iterate through your checkboxlist and test the selected value for each item and build a string containing each of your options.
string queryparam = '';
for (int i=0; i<checkboxlist1.Items.Count; i++) {
if (checkboxlist1.Items[i].Selected)
{ queryparam += (queryparam.Length = 0) ? "id = " + checkboxlist1.Items[i].Text : " or id = " checkboxlist1.Items[i].Text }
}
This should give you an idea to start with.