I'm deleting a single database record from a listview and after deleting I try to navigate in my listview using listView1.selectedindex property, but I have noticed that it highlights the incorrect record (for example I set listView1.selectedindex to 1 but it displays a record which has index 0) . What is wrong? Please help!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView method looks so:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
Instead of using deleteButton_Click event you could use your ListView's OnItemCommand event to get the selected row values and delete the item that you want like the code below:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
And on your control's element will look like this:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
Let me know if you still have issue with it.
Related
I have a drop down list ; a sqldatasource and a gridview .
I want to fill the grid view by the choice in the drop down list.
How can i implement this fill ?
Thanks
My question is not a duplicate of this Click
because it want to populate a drop down list inside the grid view instead my question is : by a choice of a drop down list , fill a grid view.
EDIT (Because i am in negative rep.) :
What i have tried
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
aspx page
<asp:DropDownList runat="server" ID="drp" AutoPostBack="true" OnSelectedIndexChanged="drp_SelectedIndexChanged"></asp:DropDownList>
<asp:GridView runat="server" ID="grd" AutoGenerateColumns="true"></asp:GridView>
code behind of aspx
protected void drp_SelectedIndexChanged(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
grd = dataSource;
grd.DataBind();
}
Bind grid on selection index change event of dropdown.
This is my one tag:
<asp:Button ID="button" runat="server" Text="ShowOrder" onclick="newTab" />
This is my 'aspx.cs' which will be called when button is clicked
protected void newTab(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?id="+txtSearchCustomerByID.Value);
}
What I want is to print my sql table on loaded web tab (new page) when it gets loaded.
My stored procedure is displaying the data of my table where id is equal to "id entered by user in textbox".
Now,
protected void Page_Load(object sender, EventArgs e)
{
int id_no = int.Parse(Request.QueryString["id"]);
if (Page.IsPostBack)
{
showOrders(id_no);
}
}
Now what should I have in 'Default2.aspx' so that I will get my table by using,
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand("showOrdersSP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
con.Open();
.......
}
}
I need to use DataTable
So simply when I clicked, I will get data table on new page
You can refer below code:
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
DataTable dt = new DataTable();
SqlParameter[] p1 = new SqlParameter[1];
p1[0] = new SqlParameter("#id", id);
dt= getRecords_table("showOrdersSP", p1); // you will get your DataTable here
}
}
// Common Method for FillYour Tables
private DataTable getRecords_table(string spname, SqlParameter[] para)
{
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["connName"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(spname, con);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
ad.SelectCommand.Parameters.AddRange(para);
con.Open();
ad.Fill(dt);
con.Close();
return dt;
}
Hope it will helps you
Thanks
I have a form and 'Add' button. when i click on add then i insert data into database and also i have sqldatasource in which i specify only select,update,delete commands. when i insert data on Add button then i want to refresh and fill the grid automatically.
my sqldatasource id is "sqldatasourceDenter" and i have specified it in my gridview datasourceID="sqldatasourceDenter".
i have tried this
GridView1.DataSourceID = sqldatasourceDenter;
it gives me the error cannot convert sqldatasource to string
i have also defined datasource but it tells both me both datasource, datasourceID cannot be defined.
I actually want to insert data on my 'Add' button then refresh the sqldataSourceDenter to fill the grid.
This is my add button click event function:
..... add_Click(object sender, EventArgs e){
..
.... /* here i have other code*/
.....
else {
string dentername = dname.Text.ToString();
string denteraddress = daddress.Text.ToString();
string dentercontact = dcontact.Text.ToString();
//create sql inset query and take to insert query ftn for execution
string dquery = string.Format("INSERT INTO Denters(D_NIC, D_Name, D_Address, D_Contact) VALUES('{0}','{1}','{2}','{3}')", denternic, dentername, denteraddress, dentercontact);
InsertIntoDB.InsertQuery(dquery);
if (InsertIntoDB.count > 0)
{
gvDenter.DataSourceID = SqlDataSourceDenter;
Response.Write("<script>alert('Denter added successfully')</script>");
InsertIntoDB.count = 0;
ClearDenterFields();
}
}
}
My aspx code is:
<asp:SqlDataSource ID="SqlDataSourceDenter" runat="server" ConnectionString="<%$ ConnectionStrings:VehiclesSystemConnectionString2 %>"
SelectCommand="SELECT [D_NIC], [D_Name], [D_Address], [D_Contact] FROM [Denters]">
</asp:SqlDataSource>
<asp:GridView ID="gvDenter" Visible="False" DataKeyNames="D_NIC" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceDenter" >
</asp:GridView>
You can have something like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataToGrid();
}
}
protected void BindDataToGrid()
{
string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(conString))
{
string myQuery = "SELECT * FROM MYTABLE";
SqlCommand cmd = new SqlCommand(myQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Add(object sender, EventArgs e)
{
//Insert To DB Code here
}
I have DropdownList which I populate at the time of Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select distinct sname from contacts where sname is not null";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
DropDownList2.DataSource = table;
DropDownList2.DataValueField = "sname";
DropDownList2.DataTextField = "sname";
DropDownList2.DataBind();
}
}
Now I am trying to populate a GridView when the DropDownList's Item changes
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string val = DropDownList2.SelectedValue;
string sqlQuery = "SELECT distinct DUTY_DATE FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE and SYSDATE+30 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL and contacts.sname = '" + val + "' ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
I have enabled the AutoPostBack. Now when I am changing a DropDownList item to a different one the Page is loading but always retaining the first value. I tried to debug , I found that
string val = DropDownList2.SelectedValue;
the val variable is always the first value that is returned by the Query. Can anybody please tell me how could I get rid of this. I want to populate the GridView whenever I am selecting any item in the dropdown.
Hi i think that dropdownlist charge again when you select other item. Put a Break Point in Page Load and look if your dropdownlist charge again i don't see other reason. Good Luck
Your Drop downlist should look like as following :
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
Make sure AutoPostBack is Set to TRUE.
One more thing you can try is to select the item when the index is greater than -1.
if(DropDownList2.SelectedIndex != -1)
{
string val = DropDownList2.SelectedItem.Value;
// enter code here
}
I have a DropDownList populated from a Database.
When I select an item in the DropDownList, I want to call a procedure and pass the value of the DropDownList to the calling procedure to query a database to populate a couple of Text Boxes.
How to do this?
Code for procedure:
protected void PopulateTextBoxes()
{
SqlDataReader MyReader;
SqlConnection Conn;
SqlParameter TourIdParam;
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;
Conn = new SqlConnection(strConnection);
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = "SELECT TourId, TName, TDetails FROM Chinatowndb.dbo.Tour Where TourId = #TourIdp";
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = Conn;
TourIdParam = new SqlParameter();
TourIdParam.ParameterName = "#TourIdp";
TourIdParam.SqlDbType = SqlDbType.Int;
TourIdParam.Direction = ParameterDirection.Input;
TourIdParam.Value = ddlTour.SelectedItem.Value;
MyCommand.Parameters.Add(TourIdParam);
MyCommand.Connection.Open();
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (MyReader.Read())
{
tbTourName.Text = (string)MyReader["TName"];
tbTourDetails.Text = (string)MyReader["TDetails"];
lblTourId.Text = Convert.ToString(MyReader["TourId"]);
}
}
Code to populate DropDownBox:
private void PopulateTour()
{
DataTable dtTour = new DataTable();
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnection))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT TourId, TName FROM Chinatowndb.dbo.Tour", con);
adapter.Fill(dtTour);
ddlTour.DataSource = dtTour;
ddlTour.DataValueField = "TourId";
ddlTour.DataTextField = "TName";
ddlTour.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item
ddlTour.Items.Insert(0, new ListItem("<Select Tour>", "0"));
}
You need to add the event handler for the selection change in your HTML
<asp:DropDownList id="ddlTour"
AutoPostBack="True"
OnSelectedIndexChanged="ddlTour_SelectedIndexChanged"
runat="server">
and process the event in your code behind
void ddlTour_SelectedIndexChanged(Object sender, EventArgs e)
{
// Call the method that gets the current item from the dropdown and fills the textboxes
PopulateTextBoxes();
}