Asp.net Cascading delete into Gridview_Rowdeleting event - c#

I have a problem that to deleting record from database. I want to delete with using Id but it has been exist other tables as foreign key. That's why I need to delete with extension.
I need to delete record from 3 tables which are Conferences, Conferences_Rewivers, Topics.
My codes like that but it throws error because of it doesn't delete records from all tables. How can I fix it?
protected void GridView1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source = ---\\SQLEXPRESS; Initial Catalog = --; Integrated Security = True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete FROM Conferences where Id = #Id";
cmd.Connection = cn;
cmd.Parameters.AddWithValue("#Id", GridView1.DataKeys[e.RowIndex].Value);
cn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Conferences_Rewivers where fk_Conferences = #Id";
cmd.ExecuteNonQuery();
cmd.CommandText = "delete from Topics where fk_Conferences = #Id";
cmd.ExecuteNonQuery();
cn.Close();
BindGridView();
}
BindGridView
if(Session["user"] != null)
{
user = Session["user"] as User;
}
SqlCommand cmd = new SqlCommand("select Conferences.Id, Conferences.conferenceName, Conferences.conferenceDate , Conferences.conferencePlace, Conferences.submissionDueDate , Conferences.category, Conferences.status, Conferences.conferenceDescription from Conferences inner join Users on Conferences.fk_Users = Users.Id where Users.Id = #UserId", conn);
SqlParameter prm = cmd.Parameters.AddWithValue("#UserId", user.Id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
conn.Close();
if(dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

First you delete foreign key tables(Conferences_Rewivers,Topics) after that you can delete main table(primary key table i.e Conferences)

Related

Search in the database

This Messages form display table with these informations (ID,FROM,TO,TITLE,MESSAGE).
I am trying to search for all the messages send to a certain user . user will enter his name in the Search_textBox then it will filter the table to keep only messages to this user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where To =" + Search_textBox.Text;
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
I get this error :
System.Data.SqlClient.SqlException: 'Invalid column name 'To'.'
What does the "search_name" parameter contains? The Message? The Column Name?
Your query is
Select * from MessagesTable where " + search_name + " = #From"
Then you specifies the "search_name" as a parameter for the #From...
So I believe your input was "Name" and your query is looked like this now:
Select * from MessagesTable where Name = 'Name';
You do not have any Name column in this specified table as you described.
this is Correct
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where [To]= #To";
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
You can change it as follows. Of course, if I understand correctly, that you want to search in the messages field by the input you get from the user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where MESSAGE = #From";
cmd.Parameters.AddWithValue("#From", search_name);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
Try with To, because "To" - keyword SQL:
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where [To] =" + Search_textBox.Text;

c# populating multiple combo box for update and delete question

this combo box gets the job id from the database and assigns it to the jobidcombobox.
private void filljobid()
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT job_id FROM job";
DataSet ds = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(ds);
con.Close();
jobidcombobox.DisplayMember = "job_id";
jobidcombobox.ValueMember = "job_id";
jobidcombobox.DataSource = ds.Tables[0];
}
And then this indexchange code takes the jobidcombobox value and uses it it to query to get the rest of the columns that relate to it.
private void jobidcombobox_SelectedIndexChanged(object sender, EventArgs e)
{
string JobID = jobidcombobox.Text;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * from job where job_id = '" + JobID + "' ";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
customeridcombobox.Text = ds.Tables[0].Rows[0]["customer_id"].ToString();
depotidcombobox.Text = ds.Tables[0].Rows[0]["depot_id"].ToString();
startlocationtextbox.Text = ds.Tables[0].Rows[0]["start_location"].ToString();
endlocationtextbox.Text = ds.Tables[0].Rows[0]["end_location"].ToString();
jobtypecombobox.Text = ds.Tables[0].Rows[0]["job_type"].ToString();
}
else
{
MessageBox.Show("Invalid job number");
}
}
As seen above the customerid is filled but only with a single value which relates to the jobid. I would like to add other customer id values in here from the database. I have tried to same function as jobid to get the customer id but i cant make it relate to the job id.
Is there any way to do this?
Try this...
Fill the job id and customer id boxes.
private void FillJobIdAndCustomerId()
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT job_id, customer_id FROM job";
DataSet ds = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(ds);
con.Close();
var dataRows = ds.Tables[0].AsEnumerable();
jobidcombobox.DisplayMember = "job_id";
jobidcombobox.ValueMember = "job_id";
jobidcombobox.DataSource = dataRows.Select(x=>x.job_id);
customeridcombobox.DisplayMember = "customer_id";
customeridcombobox.ValueMember = "customer_id";
customeridcombobox.DataSource = dataRows.Select(x=>x.customer_id);
}
And then when the a job id is selected...
private void jobidcombobox_SelectedIndexChanged(object sender, EventArgs e)
{
string JobID = jobidcombobox.Text;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * from job where job_id = #jobId";
commandObject.Parameters.AddWithValue("#jobId", JobID);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
customeridcombobox.SelectedIndex = customeridcombobox.FindString(ds.Tables[0].Rows[0]["customer_id"].ToString());
depotidcombobox.Text = ds.Tables[0].Rows[0]["depot_id"].ToString();
startlocationtextbox.Text = ds.Tables[0].Rows[0]["start_location"].ToString();
endlocationtextbox.Text = ds.Tables[0].Rows[0]["end_location"].ToString();
jobtypecombobox.Text = ds.Tables[0].Rows[0]["job_type"].ToString();
}
else
{
MessageBox.Show("Invalid job number");
}
}
Can follow similar pattern for other combo boxes you have (dept, jobtype from your example) if you would like to.
Note: You may have observed that I changed the query building slightly, using SqlParameters. The way it was written in your sample code is a classic case of SQL Injection.

Fetch data from database based on checkbox on button click

I have table consisting columns(....,....,....,BLOCK) in my database.
The BLOCK column has bit datatype(True,False).
When BLOCK column has False, the data should be fetched from the database.
When BLOCK column has True, the data should not be fetched resulting in throwing an error.
When I give the name of a particular person in textbox and click button, the above operation must be performed
my button click c# coding is...
protected void ImageButton5_Click(object sender, ImageClickEventArgs e)
{
string selectsql = "SELECT * FROM UserDetailsTwo";
using (SqlConnection con = new SqlConnection(#"Data Source=ENTERKEY001;Initial Catalog=ContactManagement;Integrated Security=True"))//DataBase Connection
{
SqlCommand selectCommand = new SqlCommand(selectsql, con);
con.Open();
SqlDataReader SelectReader = selectCommand.ExecuteReader();
while (SelectReader.Read())
{
Boolean BLOCK = Convert.ToBoolean(SelectReader["BLOCK"]);
if (BLOCK == false)
{
//con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SearchUser";
cmd.Parameters.AddWithValue("#NAME", TextBox4.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
else
{
Response.Write("Error");
}
}
SelectReader.Close();
}
}
You are trying to use an SQLDataReader like a DataAdapter.
SelectReader = selectCommand.ExecuteReader();
while (SelectReader.Read())
{
Int64 BLOCK = Convert.ToInt64(SelectReader["BLOCK"]);
if (BLOCK == false)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SearchUser";
cmd.Parameters.AddWithValue("#NAME", TextBox4.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataBind();
con.Close();
}
else
{
Response.Write("Error");
}
}
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader%28v=vs.110%29.aspx

AjAX Rating Control storing and fetching from database using repeater in asp.net c# i

I got error:
Specified cast is not valid.
I need to repeat every user already rating star from database how to get rating from db. Here how to take rating from database.
Here is the stored procedure:
ALTER PROCEDURE [dbo].[sp_comments]
(
#eid int
)
AS
BEGIN
declare #sql varchar(max)
SET NOCOUNT ON;
select #sql='select g.username,dbo.fn_username(g.updation) as updation,
c.comment_id,c.id,c.comments,c.commented_by,c.mail,c.date,c.rating_star
from comments c
inner join tbl_data as g on g.id=c.id
WHERE c.id=''' +CONVERT(VARCHAR(50),#eid) +''' order by comment_id desc'
exec(#sql)
print(#sql)
END
Here is my asp.net Design page:
<asp:Rating ID="user_rating" runat="server" CurrentRating='<%#Eval("rating_star")%>' RatingDirection="LeftToRightTopToBottom" StarCssClass="ratingStar" WaitingStarCssClass="SavedRatingStar" FilledStarCssClass="FilledRatingStar"
EmptyStarCssClass="EmptyRatingStar" AutoPostBack="true"></asp:Rating>
Here is the code behind - C# of the page
protected void Button1_Click(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
int id;
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("sp_usercomment", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mail", mail_by.Text);
cmd.Parameters.AddWithValue("#comments", comments.Text);
cmd.Parameters.AddWithValue("#name", name_by.Text);
cmd.Parameters.AddWithValue("#updated_name", Convert.ToInt32(Request.Cookies["userid"].Value));
cmd.Parameters.AddWithValue("#eid",id);
cmd.Parameters.AddWithValue("#rating",SqlDbType.Int).Value=rating.CurrentRating;
cmd.ExecuteNonQuery();
con.Close();
Label2.Visible = true;
Label2.Text = "Thanks for your valuable feedback";
mail_by.Text = "";
comments.Text = "";
name_by.Text= "";
getcomments();
}
}
void getcomments()
{
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("sp_comments", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#eid", Request.QueryString["id"].ToString()));
da=new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
con.Close();
comment_label.Text = "View " + dt.Rows.Count.ToString() + " Comments";
if (dt.Rows.Count > 0)
{
DataRow dr=dt.Rows[0];
repeat.DataSource = dt.DefaultView;
repeat.DataBind();
review_panel.Visible = true;
product = dr["username"].ToString();
}
else
{
review_panel.Visible = false;
}
}
try this,
con = new SqlConnection(str);
con.Open();
cmd = new SqlCommand("sp_comments", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#eid",Request.QueryString["id"].ToString()));
da=new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
con.Close();
DataTable dtCloned = dt.Clone();
dtCloned.Columns[3].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
repeat.DataSource = dtCloned;
repeat.DataBind();
note : here "3" in dtCloned.Columns[3].DataType will be your column number where rating_star columns is coming in your datatable.

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

Categories

Resources