<asp:UpdatePanel ID="upExec" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<button type="button" runat="server" id="btnExec" onserverclick="btnExec_Click" class="btnAll btnExec">Execute SQL Job</button>
<asp:Label ID="lblEMsg" runat="server" ClientIDMode="Static" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="upGV" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView EmptyDataText="No Provider Exists" ID="gvData" runat="server" ClientIDMode="Static" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderStyle-Width="5%" DataField="Name" HeaderText="Name" />
<asp:BoundField HeaderStyle-Width="5%" DataField="ID" HeaderText="ID" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
if (!Page.IsPostBack)
{
ViewState["sortOrder"] = "Asc";
ViewState["sortExp"] = "Due Date";
ShowGridView("Name", "Asc");
}
public void ShowGridView(string sortExp, string sortDir)
{
using (SqlConnection sc = new SqlConnection(gloString))
{
try
{
sc.Open();
SqlDataAdapter sda = new SqlDataAdapter(strQuery, sc);
DataSet ds = new DataSet();
sda.Fill(ds);
DataView dv = new DataView();
dv = ds.Tables[0].DefaultView;
gvData.DataSource = dv;
gvData.DataBind();
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
upGV.Update();
}
public void btnExec_Click(object sender, EventArgs e)
{
using (SqlConnection sc = new SqlConnection(gloString))
{
try
{
sc.Open();
using (SqlCommand scd = new SqlCommand())
{
scd.CommandText = "MySP";
scd.CommandType = CommandType.StoredProcedure;
scd.Connection = sc;
scd.ExecuteNonQuery();
}
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
using (SqlConnection sc = new SqlConnection(floString))
{
try
{
sc.Open();
SqlCommand scd = new SqlCommand();
scd.CommandType = CommandType.StoredProcedure;
scd.Connection = sc;
scd.CommandText = "msdb.dbo.sp_start_job";
scd.Parameters.AddWithValue("#job_name", "JobName");
using (scd)
{
scd.ExecuteNonQuery();
ShowGridView("Name", "Asc");
}
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
upExec.Update();
}
When the page first loads, I can see the GridView. When I click the btnExec, the GridView disappears and it displays "No Provider Exists". When I check the source of the page the data is still there.
How can I resolve it so when the button is clicked, it performs the stored procedure and reloads the GridView with the new data.
Looks like you should move the call to ShowGridView() in your btnExec_Click() method to outside the outer "using" statement, right before the call to upExec.Update().
On my case, I had to add this attribute to the panel that was wrapping my GridView to keep it visible and working, every time I was clicking on a row to select it, it kept disappearing :
<asp:Panel EnableViewState="True">
Related
So I want to make my dropdownlist to have always the same index selected, for example I have a gridview and I have a pager on it, if I change the page the index I had in my dropdownlist resets and I can give other example, I have a search textbox in my page and if I search something on it when I press enter the dropdownlist resets once again. How can I make my dropdownlist to have always the same selected index?
asp.net
<asp:GridView ID="MyGrid" runat="server"
DataKeyNames="No_" AutoGenerateColumns="false" Style="color: Black; border-collapse: collapse; margin-right: auto; display: table; text-align: center;" OnPageIndexChanging="MyGrid_PageIndexChanging" OnRowDataBound="MyGrid_RowDataBound" AllowPaging="True" OnPageIndexChanged="MyGrid_PageIndexChanged" PageSize="10" AllowCustomPaging="False">
<Columns>
<asp:BoundField DataField="No_" HeaderText="No_Encomenda" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First" LastPageText="Last" />
<PagerStyle CssClass="gridview" HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
cs
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
List<string> MySelected;
protected void Page_Load(object sender, EventArgs e)
{
ButtonBack.Visible = false;
//GridView1.Visible = false;
con.Open();
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
if(IsPostBack == false)
{
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
}
if (IsPostBack == false)
{
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
string user = Convert.ToString(Session["user"]);
username.Text = user;
if (Session["user"] == null || Session["login"] == null)
{
Response.Redirect("Login.aspx", false);
}
if (!Page.IsPostBack)
{
refreshdata();
refreshdata();
}
con.Close();
}
public void LoadGrid()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
In Page_Load code, I see that you are loading data in dropdownlist. When the page is submitted, Page_Load will execute and it will reload the data in the dropdown list. That's why selection goes off.
You should load the data in the dropdown list only during first load of the page. As you are doing with LoadGrid(). During post back the data of the dropdown and selection will be maintained if you don't reload them.
So I suggest following code change for loading data in dropdown list.
if(!IsPostBack)
{
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
I hope this will help you solve your problem.
hi i tried to display image from sql table to gridview but its not displaying this is my code to bind gridview with sql table records.....
When the user login , the user login photo should display thats y i am trying
the image already stored in database but there is an ISSUE to retrive the image from database to gridview
PostBookChat.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblsession.Text = "Welcome" + Convert.ToString(Session["UName"]);
sessionimage();
}
}
private void sessionimage()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
try
{
int EmpID = (int)Session["EmpID"];
SqlDataAdapter Adp = new SqlDataAdapter("select EmpID,Photo from TBL_PBLogin where EmpID='" + EmpID + "'", con);
DataTable Dt = new DataTable();
con.Open();
Adp.Fill(Dt);
gridviewphoto.DataSource = Dt;
gridviewphoto.DataBind();
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
PostBookChat.aspx
<body>
<form id="form1" runat="server">
<div>
<div id="header">
<img src="Image/book.png" height="60" width="140" style ="margin-left:0px;float:left;"/>
<div id="login">
<b><asp:Label ID="lblsession" runat="server" ForeColor="white" CssClass="label"></asp:Label>
<asp:GridView ID="gridviewphoto" runat="server" AutoGenerateColumns="false" BackColor="#CC3300" ForeColor="Black" ShowHeader="false" GridLines="None">
<Columns>
<asp:TemplateField ControlStyle-Width="100" ControlStyle-Height="100">
<ItemTemplate>
<asp:Image ID="Image" runat="server" ImageUrl='<%# "~/Handler.ashx?id=" + Eval("EmpID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnlogout" runat="server" Text="Sign Out" CssClass="myButton" OnClick="btnlogout_Click"/>
</div>
</div>
</body>
Handler.ashx
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["EmpID"] == null) return;
string connStr = ConfigurationManager.AppSettings["connect"].ToString();
string pictureId = context.Request.QueryString["EmpID"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROm TBL_PBLogin WHERE EmpID = #EmpId", conn))
{
cmd.Parameters.Add(new SqlParameter("#EmpID", pictureId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Photo")]);
reader.Close();
}
}
}
}
DataBase
EmpID (PK,int notnull) (1,1)
UName(varchar(255),notnull)
Password(varchar(255),notnull)
Photo(image,null)
I am working with Asp.Net C# and want to take the id of the row with a checkbox from the GridView.
With the code above if is checked the only think i am getting with debug is:
chk: {Text = "" Checked = false}
What i am doing wrong and how i can fix this?
<!-- language: lang-css -->
protected void Page_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
if(!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
string user = Session["user"].ToString();
using (MySqlConnection con2 = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT RouteNo,sender FROM routedoc WHERE Recipient = #user ", con2);
adp.SelectCommand.Parameters.AddWithValue("?user", user);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "sender";
DropDownList1.DataValueField = "RouteNo";
DropDownList1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// Response.Write(GridView1.SelectedRow.Cells[1].Text);
foreach(GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("box") as CheckBox ;
if (chk.Checked)
{
var id = row.FindControl("RouteNo") as Label;
Response.Write(id.Text);
}
}
}
routedoc.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="routedoc.aspx.cs" Inherits="WebApplication2.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>page 2<asp:DropDownList ID="DropDownList1" runat="server" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="136px" >
</asp:DropDownList>
</h1>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Recipient,DocHandle,Sender" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="RouteNo" HeaderText="RouteNo" InsertVisible="False" SortExpression="RouteNo" />
<asp:BoundField DataField="Recipient" HeaderText="Recipient" ReadOnly="True" SortExpression="Recipient" />
<asp:BoundField DataField="DocHandle" HeaderText="DocHandle" ReadOnly="True" SortExpression="DocHandle" />
<asp:BoundField DataField="Sender" HeaderText="Sender" ReadOnly="True" SortExpression="Sender" />
<asp:BoundField DataField="TermNo" HeaderText="TermNo" SortExpression="TermNo" />
<asp:BoundField DataField="SentDate" HeaderText="SentDate" SortExpression="SentDate" />
<asp:BoundField DataField="DueDate" HeaderText="DueDate" SortExpression="DueDate" />
<asp:BoundField DataField="SentTime" HeaderText="SentTime" SortExpression="SentTime" />
<asp:BoundField DataField="DueTime" HeaderText="DueTime" SortExpression="DueTime" />
<asp:BoundField DataField="Action" HeaderText="Action" SortExpression="Action" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="BUDate" HeaderText="BUDate" SortExpression="BUDate" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate><asp:CheckBox ID="Box" runat="server"/>
</ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:imagingConnectionString %>" ProviderName="<%$ ConnectionStrings:imagingConnectionString.ProviderName %>" SelectCommand="SELECT * FROM routedoc "></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Height="43px" OnClick="Button1_Click" Text="DELETE" Width="109px" />
</form>
</body>
</html>
This is caused by the fact that you always bind your GridView1 with data,
even on post-back. This is causing that all check box-es remain unchecked.
Remove grid loading if you are in post-back, and it should work fine.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
BindDropDown();
}
}
If you, however, need to load grid even in post-back, I will tell you a fix for that.
Whenever you bind a data to a data control in Page_Load event, please consider using Page.IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// bind data
}
}
This is because, when you click a button, your page will be still refreshed, which means you will bind the same data to gridview again, resulting in unchecked checkboxes. You can check whether the page is loaded by a button click (Page.IsPostBack) or the page is loaded the first time (!Page.IsPostBack), and do your data binding accordingly.
Hope this makes sense!
I have a Gridview on which I have Edit option for editing the Row. I have written the code for Edit and Update but it is not getting updated and the row gets blank. I debugged the code and didn't got to know what was the exact problem. Please see the code for your ref and let me know what is the exact issue:-
Gridview aspx code:
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False"
AllowPaging="true" PageSize="4" CssClass="hoverTable" OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowDataBound="grdPostData_RowDataBound"
OnRowDeleting="grdPostData_RowDeleting" DataKeyNames="Id" OnRowEditing="grdPostData_RowEditing" OnRowUpdating="grdPostData_RowUpdating"
OnRowCancelingEdit="grdPostData_RowCancelingEdit" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>' > </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
</asp:GridView>
Also see the CS code:
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
// DropDownList ddlPostlistcategory = ((DropDownList)(row.Cells[0].Controls[0]));
TextBox txtPostTitle = ((TextBox)(row.Cells[0].Controls[0]));
TextBox txtPostdesc = ((TextBox)(row.Cells[1].Controls[0]));
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
grdPostData.DataBind();
}
}
protected void grdPostData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdPostData.EditIndex = -1;
BindGrid();
}
Edited part of the code:-
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = grdPostData.Rows[e.RowIndex];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory");
//TextBox title = ((TextBox)(row.Cells[0].Controls[0]));
//TextBox description = ((TextBox)(row.Cells[1].Controls[0]));
TextBox title = (TextBox)row.FindControl("txtPostTitle");
TextBox description = (TextBox)row.FindControl("txtPostdesc");
DropDownList ddlActive = (DropDownList)row.FindControl("ddlActiveInactive");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_post SET title=#title,description=#description,active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
grdPostData.EditIndex = -1;
grdPostData.DataBind();
}
}
Code Is perfect just small mistake.
Change
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
To
TextBox ddlActive = ((TextBox)(row.Cells[3].Controls[0]));
You want to set value of Active which is 3rd control not 2nd.
If Your control is in TemplateField then you have find control from row
For DropDownList You need to try something like this:
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
Following Line will generate error
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
You need to find this control ddlActiveInactive from grid which you are missing
Don't Use AddWithValue it gives Unexpected Results Sometimes
SOURCE
EDIT:
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
string PostTitle = row.Cells[0].Text;
string Postdesc = row.Cells[1].Text;
string Active = row.Cells[2].Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.Add("#Id",SqlDbType.Int).Value=Id;
cmd.Parameters.Add("#title",SqlDbType.Varchar,100).Value=PostTitle ;
cmd.Parameters.Add("#description",SqlDbType.Varchar,200).Value= Postdesc ;
cmd.Parameters.Add("#Active",SqlDbType.Int).Value=Convert.ToInt32(Active);
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
//GET GDATA FROM DATABASE AND BIND TO GRID VIEW
}
}
I have an access DB (.mdb) named: Programs, with one table named: Data. By using the DataGridView I present the data from the table Data. I want to delete a row from the DataGridView and from the DB during runtime. Does anyone know how to do that (using C#)?
Another question I have is, who can i run queries on my DB?
thanks!
Very simple.
I suppose in your datagrid you have a check box by choosing which you will be able to choose the rows that you want to delete. And assuming you have a submit button, so after choosing the rows click on the submit button. In the button's click event call the Delete query say delete from tblname where id = #id [#id is the id that will be passed from your grid]
After that just populate the grid e.g. select * from tblname
e.g.
Aspx code
<asp:GridView runat="server" ID="gvTest" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="RegID" DataField="RegID" ItemStyle-Width="10%">
<ItemStyle HorizontalAlign="Left"/>
</asp:BoundField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="22%" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Width="100%" Text= '<%# DataBinder.Eval(Container.DataItem, "UserName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
Submit button cilck event's code
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int count = 0; count < gvTest.Rows.Count; count++ )
{
CheckBox chkSelect = (CheckBox)gvTest.Rows[count].FindControl("chkDel");
if (chkSelect != null)
{
if (chkSelect.Checked == true)
{
//Receiveing RegID from the GridView
int RegID = Int32.Parse((gvTest.Rows[count].Cells[1].Text).ToString());
object result = DeleteRecord(RegID); //DeleteRecord Function will delete the record
}
}
}
PopulateGrid(); //PopulateGrid Function will again populate the grid
}
public void DeleteRecord(int RegId)
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlConnection connection = new SqlConnection(#connectionPath);
command = "delete from tblname where id = " + RegId
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(command, connection);
cmd.ExecuteNonQuery();
}
catch (SqlException sqlExcep) {}
finally
{
connection.Close();
}
}
public void PopulateGrid()
{
DataTable dt = new DataTable();
dt = GetRecord();
if(dt !=null && dt.rows.count>0)
{
gvTest.DataSource = dt;
gvTest.DataBind();
}
}
public DataTable GetRecord()
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection connection = new SqlConnection(#connectionPath);
command = "Select * from tblname" ;
connection.Open();
SqlCommand sqlCom = new SqlCommand(command, connection);
adapter.SelectCommand = sqlCom;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
Hope this makes sense.