I need to delete a row from gridview and database based on it's id which is unique identifier.
In my code below I get error msg " Unrecognized Guid format" .Any help to fix it?
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = GridView1.Rows[e.RowIndex].Cells[0].Text;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("Delete", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#ID", SqlDbType.UniqueIdentifier);
command.Parameters["#ID"].Value = new System.Guid(id);
command.Connection.Open();
command.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
command.Connection.Close();
}
Try this:
Guid theGuid = new Guid();
System.Data.SqlTypes.SqlGuid.Parse(theGuid.ToString());
Adding a Guid Parameter into SqlCommand
Use Guid.TryParse on your id string, then you'll know what's going on.
Related
can anybody help?
I have two stored procs, each calling two separate result tables.
I need to create a dropdown list so when a table is selected it will refresh the page and populate the grid view with the new table result...
at the moment all i have is the connection calling one of the tables on the page load... but i need this populating to the dropdown list also...
public void Refreshdata()
{
SqlConnection con = new SqlConnection(#"Server=(LocalDB)\v11.0;Database=WorkstationCells");
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "dbo.uspTargetQuantitesg120";
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cmd.Parameters.Add("#Product", SqlDbType.VarChar, 10).Value = "g120C";
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
I know similar questions have been answered but i am new to this and not sure where to start.
First create a drop down list in your form and set AutoPostBack=true
<asp:DropDownList ID="DropDownlist1" runat="server" AutoPostBack="true"
Width="200px" onselectedindexchanged="DropDownlist1_Changed">
</asp:DropDownList>
Refreshdata()
void Refreshdata()
{
SqlConnection con = new SqlConnection(#"Server=(LocalDB)\v11.0;Database=WorkstationCells");
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "dbo.uspTargetQuantitesg120";
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
cmd.Parameters.Add("#Product", SqlDbType.VarChar, 10).Value = "g120C";
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Void DropDown()
void DropDown()
{
con.Open();
String str = "Your Query";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery()
con.Close();
}
Page_Load()
if (!IsPostBack)
{
DropDown();
}
}
DropDownlist1_Changed()
protected void DropDownlist1_Changed(object sender, EventArgs e)
{
Refresh();
}
Please try this to bind data to DropDownList in GridView in ASP.Net
https://www.aspsnippets.com/Articles/How-to-bind-data-to-DropDownList-in-GridView-in-ASPNet.aspx
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
connection db_obj1 = new connection();
SqlConnection sql_obj = db_obj1.Connect();
if (this.DropDownList1.SelectedIndex >= 0)
{
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
// SqlDataReader query_read = query.ExecuteReader();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataTable table = new DataTable();
adapter.SelectCommand = command;
adapter.Fill(table);
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
}
}
The problem is that when I run the code, I only see the drop down list and no GridView even when I select dofferent options. I tried debugging and it seems that the table DOES get filled and the only problem that I think is in the line 'grd.FindControl("GridView1").Is this the proper way to give a gridview a data source?
According to me you should not use like
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
on behalf that try as below
string brand = DropDownList1.SelectedItem.Text;
after that fire a query.
i hope it will halpful.
After Edit now use this code
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataSet ds = new DataSet();
DataTable table;
adapter.SelectCommand = command;
adapter.Fill(ds, "ABC");
table = ds.Tables["ABC"];
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
Explanation
adapter.Fill(ds, "ABC");
here ABC is a temp name of table you can take anything.
table = ds.Tables["ABC"];
and write here same table name as you have taken a temp table name.
now try it.
I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.
public DataTable GetDetail(string ID)
{
if (ID == "")
{
return null;
}
else
{
DataTable Detail = null;
using (SqlConnection conn = new SqlConnection(connection))
{
string comm = #"select * from dbo.Products where ID = #ID";
conn.Open();
SqlDataAdapter adapter=null;
using (SqlCommand cmd = new SqlCommand(comm, conn))
{
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(Detail);
return Detail;
}
}
}
I think you missed the commandType
cmd.CommandType = CommandType.Text;
Try this
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
{
string myquery="select * from dbo.Products where ID = #ID";
SqlCommand cmd = new SqlCommand(myquery, con);
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
cmd.Parameters.Add("#ID", SqlDbType.NVarChar, 15).Value = ID;
dap.Fill(ds);
return ds.Tables[0];
}
Thanks for ALL.
The problem is I didnt initialize my datatable to a new instance.
DataTable Detail = null; ===> DataTable Detail = new Datatable();
and also the convert should be done in sql not in codes.
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;
string comm = #"select * from dbo.Products where ID = convert(int,#ID)";
i test my query in sql server and it's working 100%
but in my page not work !!
this my query
UPDATE Employee SET
Name='jojo',
Age=19,
GenderID=2,
CountryID=5,
Mobile=0917021092
WHERE EmployeeID=10
this my code
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEditID");
Label EmployeeID = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEmployeeID");
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
DropDownList gender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropGender");
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropCountry");
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
string stringconnectiong = ConfigurationManager.ConnectionStrings["Employee_TestConnectionString"].ConnectionString;
string sql = "update Employee set Name=#Name, Age=#Age,GenderID=#GenderID , CountryID=#CountryID , Mobile=#Mobile where EmployeeID=#EmployeeID AND ID=#ID";
SqlConnection con = new SqlConnection(stringconnectiong);
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID.Text);
cmd.Parameters.AddWithValue("#ID", id.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#Age", age.Text);
cmd.Parameters.AddWithValue("#GenderID", gender.SelectedValue);
cmd.Parameters.AddWithValue("#CountryID", country.SelectedValue);
cmd.Parameters.AddWithValue("#Mobile", mobile.Text);
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
cmd.ExecuteNonQuery();
SqlDataAdapter dr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dr.Fill(ds);
GridView1.DataSource = ds;
GridView1.EditIndex = -1;
BindGridview();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Error Updating ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
con.Dispose();
BindGridview();
}
}
Since your datasource is a dataset, you need to specify which data table within the dataset you are using via the DataMember propery. Or just use a data table as your datasource.
Replace the dataset lines with the following:
DataTable dt = new DataTable();
dr.Fill(dt);
GridView1.DataSource = dt;
In addition, use the GridView1_RowUpdated event. The GridView1_RowUpdating event is fired before the table is updated, therefore your parameter values have not been updated yet.
I am using asp.net 2008 repeater control. I am trying to refresh the repeater control when a button is clicked, it shows me duplicated values, that means its appending the same values once again. Here is my code
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConnection"].ConnectionString);
String sql;
sql = "select * from FeeCollection Where AdminNo='"+lblstano.Text+"'";
cmd = new SqlCommand(sql, con);
da = new SqlDataAdapter(sql, con);
da.Fill(ds, "FeeCollection");
dt = ds.Tables["FeeCollection"];
Repeater4.DataSource = dt;
Repeater4.DataBind();
con.Close();
}
protected void btnMedical_Click(object sender, EventArgs e)
{
LoadRepeater1();
}
I want to remove the existing data and refresh the data instead of appending.
Not sure where ds (DataSet) in instantiated. Try to instantiate the DataSet/DataTable within the LoadRepeater1() method.
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager
.ConnectionStrings["SqlServerConnection"].ConnectionString);
sql = "select * from FeeCollection Where AdminNo=#AdminNo";
cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#AdminNo",System.Data.SqlDbType.VarChar,20).Value=lblstano.Text;
da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
Repeater4.DataSource = dt;
Repeater4.DataBind();
}