Deleting is not supported by data source 'SqlDataSource1' in c# - c#

This is my cs:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
Textid.Text = gr.Cells[0].Text;
Textusername.Text = gr.Cells[1].Text;
Textclass.Text = gr.Cells[2].Text;
Textsection.Text = gr.Cells[3].Text;
Textaddress.Text = gr.Cells[4].Text;
}
else if (e.CommandName == "Deleterow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", gr.Cells[0].Text);
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.DeleteRow(id);
com.ExecuteNonQuery();
}
}
I created student details form, I want to delete the row from gridview.
When i click delete, it shows following error:
Deleting is not supported by data source 'SqlDataSource1' unless DeleteCommand is specified.
I'm new to .net. Now getting started,
May i know, what is my mistake in the above code?
Thanks,

else if (e.CommandName == "Deleterow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", gr.Cells[0].Text);
var id = Int32.Parse(e.CommandArgument.ToString());
//comment or remove below line
//GridView1.DeleteRow(id);
com.ExecuteNonQuery();
//rebind the data after delete
GridView1.DataBind();
}

Related

How to store the value of a cell from grid view to database using the select command?

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow gv = GridView1.SelectedRow;
Session["m_email"] = gv.Cells[3];
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string insert = "insert into Service_Info values(#c_email,#email,#first_name,#last_name,#contact,#licenseno,#street,#landmark,#pincode)";
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
cmd.Parameters.AddWithValue("#email",Session["m-email"].ToString());
cmd.Parameters.AddWithValue("#first_name", Session["user"].ToString());
cmd.Parameters.AddWithValue("#last_name", Session["user"].ToString());
cmd.Parameters.AddWithValue("#contact", Session["user"].ToString());
cmd.Parameters.AddWithValue("#licenseno", Session["user"].ToString());
cmd.Parameters.AddWithValue("#street", StreetText.Text);
cmd.Parameters.AddWithValue("#landmark", LandmarkText.Text);
cmd.Parameters.AddWithValue("#pincode", PincodeText.Text);
cmd.ExecuteNonQuery();
Label6.Visible = true;
Label6.Text = "Successfull...";
con.Close();
}
}
I want to store the value of a cell from the grid view to the database. I only want to store only the email cell value not all from grid view. But I am not getting a way to do so.
Try the following code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int selectedRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gv = GridView1.Rows[selectedRowIndex];
// Rest of the code
}
}

label does not behave properly

I am devleoping a online airline reservation system in which i have two dropdownlists to select source and destinations and a label .this label will show " there are no flights" if there are no matching routes retrieved from the database (in this case its sqlserver 2008).i have written the following code which tries to do so, but when i postback or refresh the page the label with " there are no flights" is till visible.what is wrong with my code please anyone help me with that.
public partial class Dropdndemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
//string Sqlcmnd="select Source from Ars2.1.2.dbo.Scheduling";
con.Open();
if (!Page.IsPostBack)
{
SqlCommand com = new SqlCommand("select distinct Source from Schedulings", con);
SqlCommand comn=new SqlCommand("select distinct Destination from Schedulings", con);
//SqlDataReader readr;
DropDownList1.DataSource = com.ExecuteReader();
DropDownList1.DataTextField = "Source";
// DropDownList1.DataTextField = "Destination";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "select Source");
con.Close();
con.Open();
DropDownList2.DataSource = comn.ExecuteReader();
DropDownList2.DataTextField = "Destination";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, "select Destination");
con.Close();
}
//con.Close();
// DropDownList1.DataBind();
//con.Close();
if (IsPostBack)
Label3.Text = "";
//Label1.Visible = false;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// string Source = DropDownList1.SelectedValue.ToString();
// Label1.Text = Source;
}
protected void Button1_Click(object sender, EventArgs e)
{
string src = DropDownList1.SelectedItem.ToString();
string desti = DropDownList2.SelectedItem.ToString();
if ((src == desti) && IsPostBack)
{
Label1.Text = "Source And Destination cant be same!";
}
SqlConnection lop = new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
lop.Open();
SqlCommand cmd = new SqlCommand("select * from Schedulings where Source=#Source and Destination=#Destination", lop);
cmd.Parameters.AddWithValue("Source", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("Destination", DropDownList2.SelectedItem.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 0)
{
Label3.Text = "No planes available in this route!!!";
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
I suppose you are refreshing page using F5 or by right clicking on page and opting refresh option or using refresh button of browser. If this is the case then I am scared it's not refresh, it's repeating previous action. That means if you were searching for flight and refreshing using above options, it will again search for flight using same search criteria. You can confirm it by putting debugger on search event. You can avoid this behavior by setting and clearing Session or ViewState and manage label text using it.

unable to get all the data display checked in datalist

I have a datalist which contain product catagory with unique ID asign to every products in my catalog. However, when i checked 2 or more checkboxes, i will only get the latest data display next page, but not all the data displayed. Just 1 data displayed only. Is there any way i can do so that I can pass 3 different ID at a time and display on nxt page?
void GetCheckedBox()
{
foreach (DataListItem li in DataList1.Items)
{
//access the check checklist
HtmlInputCheckBox cb = li.FindControl("FavChkBox") as HtmlInputCheckBox;
if (cb != null && cb.Checked)
{
ArrayList Product = new ArrayList();
LblText.Text += " , ";
LblText.Text += cb.Value;
Product.Add(cb.Value);
string url = "CompareProducts.aspx?prodId=" + cb.Value.ToString();
Response.Redirect(url);
}
}
}
CompareProducts.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Product aProd = new Product();
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * FROM Products WHERE Product_ID = #ProdID", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cmd.Parameters.AddWithValue("#ProdID", Page.Request.QueryString["ProdID"].ToString());
con.Open();
adp.Fill(ds, "Products");
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
DataList1.DataSource = ds;
DataList1.DataBind();
}
I'm not totally sure what you are saying, but based on your code I see in your ForEach loop you have a response.redirect, so in this case you will only redirect to a single ID querystring. You could switch your to use a session variable that holds a list of all the ID's the user selected.
foreach (DataListItem li in DataList1.Items)
{
//access the check checklist
HtmlInputCheckBox cb = li.FindControl("FavChkBox") as HtmlInputCheckBox;
if (cb != null && cb.Checked)
{
ArrayList Product = new ArrayList();
LblText.Text += " , ";
LblText.Text += cb.Value;
Product.Add(cb.Value);
}
Session.Add("SelectedProducts", Product);
string url = "CompareProducts.aspx?hasProducts=true;
Response.Redirect(url);
}
Then in your CompareProducts.aspx.cs on pageload if not postback check the querystring to decide if you should load the id's.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Page.Request.QueryString["hasProducts"].ToString() == "true")
{
ArrayList al = Session["SelectedProducts"] as ArrayList;
if (al == null)
throw new ApplicationException("A product list is required.");
if (al.Count < 1)
throw new ArgumentException("No products selected");
string inStatement = string.Empty;
foreach (var item in al)
{
inStatement += al.ToString() + ", ";
}
inStatement = inStatement.Substring(0, inStatement.Length - 2);
//Product aProd = new Product();
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("SELECT * FROM Products WHERE Product_ID in (" + inStatement + ")", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
con.Open();
adp.Fill(ds, "Products");
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
DataList1.DataSource = ds;
DataList1.DataBind();
}

How to Bind DropDown in GridView

I have drop-down that is in a gridview and it is binding but the problem is that is binding only the first row and keep binding the same value the rest of the gridview. I am expecting a drop down for each each row in the gridview and the content of the drop down will be different based on ID in the gridvew. In one row it might be Yes, No and the other one might be Yes, No, NA. Here is my code:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Answer;
foreach (GridViewRow grdRow in GridView1.Rows)
{
//get current index selected
int current_eng_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
ddl_Answer = (DropDownList)(GridView1.Rows[grdRow.RowIndex].Cells[2].FindControl("ddl_Answer"));
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
SqlConnection con2 = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 D, table2 Q where Q.ANS_OPT = D.ID and ENG_SK= '" + current_eng_sk + "' and Q.ANS_OPT is not null ");
cmd1.Connection = con2;
con2.Open();
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
con2.Close();
}
}
You are already in the RowDataBound event for the GridView. This is fired once per row so you don't need to then further foreach (GridViewRow grdRow in GridView1.Rows) each time through. You should be able to simplify your code down to:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Answer;
//get current index selected
int current_eng_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString))
{
con2.Open();
using (SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 D, table2 Q where Q.ANS_OPT = D.ID and ENG_SK= '" + current_eng_sk + "' and Q.ANS_OPT is not null ", con2))
{
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
}
}
}
}

error in finding control in gridview

I had gridview which on databound I need to hid Image control so I did this code but error apear( grid view dosenot containe defination of RowIndex) when i tried to find control
C# Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Img = GridView1.Rows[e.RowIndex].FindControl("Logo") as Image ;
using (SqlConnection con = Connection.GetConnection())
{
string Sql = "Select Logo From Model where Id=#Id";
SqlCommand com = new SqlCommand(Sql, con);
com.Parameters.Add(Parameter.NewInt("#Id", DDLModel.SelectedValue));
com.CommandType = CommandType.Text;
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
string Img2 = dr["Logo"].ToString();
if (Img2 == System.DBNull.Value.ToString())
{
Img.Visible = false;
}
}
}
}
GridViewRowEventArgs contains the row so you could try:
image = e.Row.FindControl("Logo") as Image;

Categories