I am trying to delete subcategory from repeater using a link button. Currently, main category deleted but i cant delete subcaegory. Help me please...
private void BindRepeater()
{
DataTable dtCategory = system.GetDataTable("Select * from TBLCATEGORIES where SubCategoryID="+CategoryID);
if (dtCategory.Rows.Count > 0)
{
rpCategory.DataSource = dtCategory;
rpCategory.DataBind();
}
}
protected void OnDelete(object sender, EventArgs e)
{
//Find the reference of the Repeater Item.
RepeaterItem item = (sender as LinkButton).Parent as RepeaterItem;
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("Delete from TBLCATEGORIES where SubCategoryID="+CategoryID);
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DeleteMsg.Visible = true;
}
}
this.BindRepeater();
}
Please find the code,hope this will help you:
protected void rpCategory_ItemCommand(object source, RepeaterCommandEventArgs e)
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["ShqiptarConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
conn.Open();
if (e.CommandName == "Delete")
{
comm = new SqlCommand("Delete from TBLCATEGORIES where CategoryID=" + e.CommandArgument, conn);
comm.ExecuteNonQuery();
}
conn.Close();
conn.Dispose();
DeleteMsg.Visible = true;
//Rebind here: this.BindRepeater();
}
Related
I wanat to retrieve student ID from database. Here is my code what i have tried but it is not displaying anything.
Thanks...
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True");
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
string str = "select * from StRecords where StID='" + Session["login"] + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label11.Text = dt.Rows[0]["StID"].ToString();
}
}
If you want to take just StudentId from the database, then you just select that column and use ExecuteScalar property.
Code
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True"))
{
con.Open();
string str = "select [StID] from StRecords where StID = #stdId;";
using (SqlCommand com = new SqlCommand(str, con))
{
com.Parameters.AddWithValue("#stdId", Session["login"]);
Label11.Text = com.ExecuteScalar().ToString();
}
}
}
Also always use parameters instead passing the value in single quotes to avoid SQL injection attack.
Also try to give the connection string in Web.Config file.
I keep on getting the Name instead of the Price.What I want is I pick a value on The DropdownList and Load its price on the label.
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
while (rdr.Read())
{
lblPrice.Text = DropDownList1.SelectedValue.ToString();
}
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
lblPrice.Text=DropDownList1.SelectedItem.Value.ToString();
}
above is my selectedIndex.
Change your code into this:
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if(dr.HasRows)
{
while (rdr.Read())
{
lblPrice.Text = rdr.GetValue(0).ToString(); // if price is string use GetString(0))
}
}
connection.Close();
}
EDIT:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GetData();
}
I want the DataGridView gets updated when DataTable changes (myAdapter.DeleteCommand = cmd;).
Please help me. Thanks
My code is:
1.
public void DoCommand(String commandText, ActionType actionType, SqlParameter[] sqlParameter)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = getConnection();
cmd.CommandText = commandText;
cmd.Parameters.AddRange(sqlParameter);
if (actionType == ActionType.Insert)
myAdapter.InsertCommand = cmd;
else if (actionType == ActionType.Update)
myAdapter.UpdateCommand = cmd;
else if (actionType == ActionType.Delete)
myAdapter.DeleteCommand = cmd;
cmd.ExecuteNonQuery();
}
}
2.
DataTable dt;
private void frmCustomers_Load(object sender, EventArgs e)
{
dt = obj.SelectCustomer();
dgCustomer.DataSource = localDt;
}
3.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
obj.DoCommand("delete from tbl_customer where customer_id = 1", ActionType.Delete);
}
I have two query's in C# running in a datagridview, one is to show all data. the other is set to display in the footer. The footer is showing, just not displaying my query.
query one (with footer)
protected void Button2_Click(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.ShowFooter = true;
dg.DataSource = dgl;
dg.DataBind();
cs.Close();
}
**query two(footer query)**
protected void dg_DataBound(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
String totalDonations = Convert.ToString(cmd.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[3].Text = totalDonations;
}
the datagrid shows query one works well, the footer even shows but it has not got any data.
Although you have it working, there are ways to improve it.
In the first method, using statement would manage the connection better:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con))
{
da.Fill(dt);
}
}
dg.ShowFooter = true;
dg.DataSource = dt;
dg.DataBind();
}
And the second method:
protected void dg_DataBound(object sender, EventArgs e)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
dg.FooterRow.Cells[3].Text = totalDonations;
}
Probably I would use GridView's RowDataBound to write into footer where I can can know the type of row:
protected void dg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
e.Row.Cells[3].Text = totalDonations;
}
}
EDIT : Here's the markup I have used to test:
<asp:GridView ID="dg" runat="server" AutoGenerateColumns="true" OnDataBound="dg_DataBound" ShowFooter="true">
</asp:GridView>
After hours of problems, I have solved it.
corrected code
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
MySqlCommand cmdtwo = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.DataSource = dgl;
dg.ShowFooter = true;
dg.DataBind();
cs.Close();
cs.Open();
string totalDonations = Convert.ToString(cmdtwo.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[7].Text = "Total £";
dg.FooterRow.Cells[8].Text = totalDonations;
}
although I am sure there is a better way of doing this, if you know please feel free to edit.
on my asp.net project, how can i refresh my gridview immediately after clicking my button.
my button has update codes.here is the codes;
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL = "UPDATE [bilgiler3] SET [HAM_FM] = ISNULL(MON,0)+ISNULL(TUE,0)+ISNULL(WED,0)+ISNULL(THU,0)+ISNULL(FRI,0)+ISNULL(SAT,0)+ISNULL(SUN,0) WHERE [DATE] BETWEEN #DATE1 AND #DATE2 AND WORK_TYPE='OUT'";
string connStr = WebConfigurationManager.ConnectionStrings["asgdb01ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = strSQL;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#DATE1", Convert.ToDateTime(TextBox1.Text));
comm.Parameters.AddWithValue("#DATE2", Convert.ToDateTime(TextBox2.Text));
try
{
conn.Open();
int i = comm.ExecuteNonQuery();
conn.Close();
if (i > 0)
{
Response.Write(" SUCCESS ");
}
else
{
Response.Write(" ERROR ! ");
}
}
catch (SqlException ex)
{
Response.Write(ex.ToString());
}
}
}
}
you maybe gonna say "you need to bind the data of your gridview" but i couldnt understand the method.
can you help me about it ?
thank you very much.
I would do the following:
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
SqlConnection sc = new SqlConnection("you connection string here Security=True");
private void loadData()
{
try
{
ds.Clear();
SqlCommand sCmd= new SqlCommand("Load your database", sc);
sda.SelectCommand = sCmd;
sda.Fill(ds, "sCmd");
datagrid.DataSource = ds.Tables["sCmd"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
something for c# beginners Youtube
Add this code on your button click
SqlConnection con = new SqlConnection("Connection string from web config");
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter("select * from EmployeeTable", con);
con.Open();
sda.Fill(ds ,"Data");
gridview1.datasource=ds.tables[0];
gridview1.DataBind();
private SqlConnection con;
private SqlConnectionStringBuilder str;
private void Form8_Load(object sender, EventArgs e)
{
loadData();
}
private void loadData()
{
str = new SqlConnectionStringBuilder();
str.Provider = "";
str.DataSource = #"source.accdb";
con = new SqlConnection(str.ConnectionString);
dataGridView1.DataSource = fillTable("Select* from yourTable");
}
private DataTable fillTable(string sql)
{
DataTable datatable = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, con))
{
da.Fill(datatable);
}
return datatable;
}
then If you want to refresh the table you put the loaddata(); in the event button_Click hope this help,
DataBind your control on success.
if (i > 0)
{
yourGridView.DataSource=YourDataSource;
yourGridView.DataBind();
Response.Write(" SUCCESS ");
}