Gridview.SelectedRow returns null - c#

This is my code for displaying the gridview:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCart();
}
}
protected void LoadCart()
{
string _connStr = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
SqlConnection SQLConn = new SqlConnection(_connStr);
SqlDataAdapter SQLAdapter = new SqlDataAdapter("SELECT M.menuItemName, M.menuItemImage,totalQuantity, M.menuItemPrice * totalQuantity Total_Price" +
" FROM Cart C INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID" +
" INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID", SQLConn);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
CartGridView.DataSource = DT;
CartGridView.DataBind();
LoadPrice();
}
protected void LoadPrice()
{
string _connStr = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
SqlConnection SQLConn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand("SELECT SUM(M.menuItemPrice * totalQuantity)tabulatedPrice" +
" FROM Cart C INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID" +
" INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID", SQLConn);
SQLConn.Open();
lbl_TotalPrice.Text = cmd.ExecuteScalar().ToString();
SQLConn.Close();
}
This is my code in attempting to retrieve a specific row, but it returns null.
protected void CartGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int result = 0;
Cart cart = new Cart();
GridViewRow row = CartGridView.SelectedRow;
string itemName = row.Cells[0].Text;
if (e.CommandName == "minusQuantity")
{
int quantity = int.Parse(row.Cells[3].Text) - 1;
if (quantity > 0)
{
cart.CartUpdateQuantity(quantity, itemName);
}
else
{
result = cart.CartDelete(itemName);
}
}
else if (e.CommandName == "addQuantity")
{
int quantity = int.Parse(row.Cells[3].Text) + 1;
cart.CartUpdateQuantity(quantity, itemName);
}
Response.Redirect("UserShoppingCart.aspx");
}
And here is my aspx file:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h1>Cart<table class="nav-justified">
<tr>
<td style="width: 860px" class="modal-lg">Product</td>
<td style="width: 698px">Images</td>
<td class="modal-lg" style="width: 1265px">Quantity</td>
<td>
Price</td>
</tr>
<tr>
<td colspan="4">
<asp:GridView ID="CartGridView" runat="server" AutoGenerateColumns="False" Width="1514px" OnRowCommand="CartGridView_RowCommand" >
<Columns>
<asp:BoundField HeaderText="Product" ShowHeader="False" DataField="menuItemName" />
<asp:BoundField HeaderText="Images" ShowHeader="False" DataField="menuItemImage" />
<asp:ButtonField ButtonType="Button" CommandName="minusQuantity" Text="-" />
<asp:BoundField HeaderText="Quantity" DataField="totalQuantity" />
<asp:ButtonField ButtonType="Button" CommandName="addQuantity" Text="+" />
<asp:BoundField DataField="Total_Price" HeaderText="Price" ShowHeader="False" />
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td style="height: 39px; " colspan="3">Total:<asp:Label ID="lbl_TotalPrice" runat="server"></asp:Label>
</td>
<td style="height: 39px; width:50px;">
</td>
</tr>
</table>
</h1>
</asp:Content>
Could this issue arise from having an Sql Table as the datasource?
I have attempted,
string itemName = CartGridView.Rows[0].Cells[0].Text;
though it did work for the 1st row, I am uncertain on where to go next for the subsequent rows.

The selected index change does not fire untill after the row command.
Why not just drop in a plane jane regular button? That way you can style the button, and just have a regular and simple click event for the button.
So, change your markup button to this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdAddQty" runat="server" Text="+"
OnClick="cmdAddQty_Click" />
</ItemTemplate>
</asp:TemplateField>
So, just type in OnClick= (in the markup, and you be prompted for create new event). the result is a simple plain jane button click.
So, then the button click code can be:
protected void cmdAddQty_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
Debug.Print("Row index click = " + gRow.RowIndex);
int quantity = int.Parse(gRow.Cells[3].Text) + 1;
// cart.CartUpdateQuantity(quantity, itemName);
}
So, you can easy pick up the row as per above.
And if you going to type "over and over" some sql, then build a helper rotuine to save world poverty, say like this:
protected void LoadCart()
{
string strSQL =
#"SELECT M.menuItemName, M.menuItemImage,totalQuantity, M.menuItemPrice * totalQuantity Total_Price
FROM Cart C
INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID
INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID";
CartGridView.DataSource = MyRst(strSQL);
CartGridView.DataBind();
LoadPrice();
}
protected void LoadPrice()
{
string strSQL =
#"SELECT SUM(M.menuItemPrice * totalQuantity)tabulatedPrice
FROM Cart C
INNER JOIN itemSelected I ON C.username + C.itemSelectedID = I.username + I.itemSelectedID
INNER JOIN menuItem M ON I.menuItemID + I.stallID = M.menuItemID + M.stallID";
lbl_TotalPrice.Text = MyRst(strSQL).Rows[0][0].ToString();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
string strCon = ConfigurationManager.ConnectionStrings["CartDB"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
Last but not least?
It is great to use and learn webforms. But, that is as long as you NOT paying for such a course, since webforms are now quite old, and while still rather popular? They are quite much now older and a legacy choice, one that been superseded by MVC and newer approaches.
So, I think WebForms are great, but NOT if you paying for books or a course in this day and age, and those peddling books and course(s) that teach webforms are really just using older outdated material, and thus taking a horrible advantage of un-suspecting students that don't know better.
Anyway, just drop in a plain jane regular button. You can dispense with row command and all that song and dance, as it not really required, and a simple regular button and button click event is easier anyway.

Related

click event for dynamic button inside a datalist

I have a DataList and bind it corrertly.
SqlCommand cmd = new SqlCommand(str_cmd, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dtlst_periodicTask.DataSource = ds;
dtlst_periodicTask.DataBind();
pds.DataSource = ds.Tables[0].DefaultView;
pds.AllowPaging = true;
pds.PageSize = 25;
pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
and some codes for paging.
After that, I need to add a number of Buttons in each row dynamically because the number of buttons is not fix.
foreach (DataListItem item in dtlst.Items)
{
Button btn = new Button();
btn.Click += new EventHandler(btn_Click);
pnl_users.Controls.Add(btn);
}
But the button click event does not work.
protected void btn_Click(object sender, EventArgs e)
{
// code does not fire.
}
When I put a Button in .aspx page, have access and it works.
protected void dtlst object source, DataListCommandEventArgs e)
{
}
but why are you attempting to inject a button?
Why not just include the button in the markup in the first place? I can't really see the need or reason to layout a datalist, and THEN decide to use code?
Just drag + drop in a button into the datalist, and you are quite much done.
So here is our datalist - we dropped in a plane jane button.
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" >
<ItemTemplate>
<div style="border-style:solid;color:black;width:300px;margin-left:25px">
<div id="mybox" runat="server" style="padding:5px;text-align:right">
<p>Hotel Name: <asp:TextBox ID="HotelName" runat="server" Text ='<%# Eval("HotelName") %>' /></p>
<p>First Name: <asp:TextBox ID="FirstName" runat="server" Text ='<%# Eval("FirstName") %>' /></p>
<p>Last Name: <asp:TextBox ID="LastName" runat="server" Text ='<%# Eval("LastName") %>' /></p>
<p>City: <asp:TextBox ID="City" runat="server" Text ='<%# Eval("City") %>' /></p>
<p>Province: <asp:TextBox ID="Province" runat="server" Text ='<%# Eval("Province") %>' /></p>
Active: <asp:CheckBox ID="Active" runat="server" Checked = '<%# Eval("Active") %>'/>
<br />
<asp:Button ID="cmdRow" runat="server" Text="Row click This item"
/>
</div>
</div>
<div style="height:15px"></div>
</ItemTemplate>
</asp:DataList>
And our code to fill looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
MyLoadData();
}
void MyLoadData()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT TOP 3 * FROM tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, con))
{
con.Open();
DataList1.DataSource = cmdSQL.ExecuteReader();
DataList1.DataBind();
}
}
And we now have this:
Now, lets wire up the button click, like this:
so, create new event in above (inteli-sense offers this choice).
protected void cmdRow_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
DataListItem gRow = (DataListItem)btn.Parent;
Debug.Print("Row index = " + gRow.ItemIndex.ToString());
int pkID = (int)(DataList1.DataKeys[gRow.ItemIndex]);
Debug.Print("Data base PK id = " + pkID.ToString());
Debug.Print("Hotel name = " + ((TextBox)(gRow.FindControl("HotelName"))).Text);
Debug.Print("City = " + ((TextBox)(gRow.FindControl("City"))).Text);
Debug.Print("--------------------");
}
And out output is this:
Row index = 1
Data base PK id = 72
Hotel name = Banff Rocky Mountain Resort
City = Banff
--------------------
so, it not at all clear why you want to spend the time, effort, and that of writing code when you can as a general rule just drop in a good old plane jane button from the designer right into the datalist, and then simple wire up a event.
Edit:
You can lead a horse to water - but can you get the horse to drink the water?
You can as noted inject a button, but I REALLY but REALLY but REALLY do not recommend doing this.
However, to get the button click event to work, then you can do this:
HtmlButton btn = new HtmlButton();
btn.InnerText = "Index " + e.Item.ItemIndex;
btn.Attributes.Add("onclick","__doPostBack('BtnTest2','')");
btn.ViewStateMode = ViewStateMode.Enabled;
HtmlGenericControl MyDiv = (HtmlGenericControl)e.Item.FindControl("mybox");
MyDiv.Controls.Add(btn);
Edit2:
Ok, there seems to be a issue of persistence.
So, adding MUST occur on page load (or could be earlier).
And the buttons have to be re-inserted each time on post-backs.
This now works:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyLoadData();
}
AddBtns();
}
void MyLoadData()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT TOP 3 * FROM tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, con))
{
con.Open();
DataList1.DataSource = cmdSQL.ExecuteReader();
DataList1.DataBind();
}
}
}
void AddBtns()
{
foreach (DataListItem gRow in DataList1.Items)
{
Button btn = new Button();
btn.Text = "Index " + gRow.ItemIndex;
btn.ID = "Btn" + gRow.ItemIndex;
btn.Click += new EventHandler(BtnTest3);
HtmlGenericControl MyDiv = (HtmlGenericControl)gRow.FindControl("mybox");
MyDiv.Controls.Add(btn);
}
}
void BtnTest3(object sender, EventArgs e)
{
Debug.Print("buttn3 click");
}
Note two changes:
We don't add/inject the buttons ONLY on !IsPostback.
We inject the buttons each time on page load
We did not use the Item bound event.

Can't get the grid view data and store it to database

<div class="container">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Size="Medium">
<asp:TemplateField HeaderText="Student ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Width="80px" Text='<%#Eval("studentID") %>'/>
</ItemTemplate>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton runat="server" OnCommand="LinkButton_Click" Text=" VoteCandidate"> </asp:LinkButton>
</ItemTemplate>
</asp:GridView>
<div>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</div>
</div>
Here is my form to show the gridview.
protected void loadCandidate()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select studentID from candidate where faculty='FOCS'", con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void LinkButton_Click(Object sender, EventArgs e)
{
String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
foreach (GridViewRow g1 in GridView1.Rows)
{
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
String query = "insert into voting (studentID)values ('" + g1.Cells[0].Text + "')" ;
MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MyConn2.Close();
}
}
When I execute the sql insert command, no error occur, but I expect the studentID that displayed in the gridview being stored in the voting table, but the studentID on the voting table are empty.
Since you use a template field in your GridView, you can't use the cell directly, you need to look for the label inside the cell like this:
foreach (GridViewRow g1 in GridView1.Rows)
{
Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
// now proceed with your inserting.
}
But if you using the loop the way you do it right now, there will be an insert for every row in the GridView, not only for the one you clicked on...
If you want to get the Id for the row the LinkButton is in, don't iterate over the rows. Instead use the NamingContainer-property of the sender like this:
LinkButton linkButton = (LinkButton)sender;
GridViewRow g1 = (GridViewRow)linkButton.NamingContainer;
Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
// now proceed with your inserting.
For more details look at this question and answer

DropDownList is not showing the Selected Value in EditItemTemplate of RadGrid

I am using asp DropDownList inside RadGrid, and trying to Add and Update the DropDownList item inside Database table.
Below is the HTML code for DropDownList inside RadGrid's EditItemTemplate:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>'></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
C# Code:
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField = "AccountDescription";
ddl.DataValueField = "AccountCodeID";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
//Select particular dropdown value while "Edit"
string accCodeID = item.GetDataKeyValue("AccountCodeID").ToString();
Label lblAcCode2 = item.FindControl("lblAcCode") as Label;
//if (!string.IsNullOrEmpty(lblAcCode2.Text))
//{
ddl.SelectedValue = lblAcCode2.Text;
//}
//string SelectedVal = ddl.SelectedValue;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCode]+' - '+[AccountDescription] as [AccountDescription] FROM [Sunway_AP].[Invoice].[tbl_AccountCodeTest] where AccountCodeID='" + accCodeID + "' ", con);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
ddl.SelectedValue = dt.ToString();
string SelectedVal = ddl.SelectedValue;
}
}
}
This is the Stored Procedure:
ALTER PROCEDURE [Invoice].[usp_tbl_AccountCode_DL_Test]
#CompanyCode nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT [AccountCodeID] ,[AccountCode]+' - '+[AccountDescription] as [AccountDescription]
FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK)
Where [CompanyCode] = #CompanyCode
order by [AccountCode]+' - '+[AccountDescription]
END
My problem is: I am unable to fetch the "DropDownList's" selected value for a particular Id (particular row of RadGrid), while Edit.
Everytime when I try to set the Selected Value of DropdownList from code behind, it shows me 1st item '- Select -' inside the selected value.
Please reply what is wrong in my code.
I am very new in Telerik. Thanks in advance.
Modified my posted code as below:
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField="*your text field*";
ddl.DataValueField="*your Value field*";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
Label lblAcCode2 = item.FindControl("lblAcCode2") as Label;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
ddl.SelectedItem.Text = lblAcCode2.Text;
ddl.SelectedValue = lblAcCode2.Text;
}
}
}
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Hope this helps...
All the best...

how to delete using checkbox in asp repeater control with button?

hi can some one help me please. My objective is to allow users to delete multiple rows in the data base called 'messages'.
By selecting the checkboxes user will be able to delete multiple rows after pressing the button.
However nothing happen when i use the codes below. Can some one help me see if there is anything wrong with my codes? Thanks =)
source code
<%# Page Title="" Language="C#" MasterPageFile="~/MainMasterPage.master" AutoEventWireup="true" CodeFile="Messages.aspx.cs" Inherits="Messages" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<SCRIPT runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
String userLog = Session["loginuser"].ToString();
if (!IsPostBack)
{
LoadData();
}
}
public void LoadData()
{
String userLog = Session["loginuser"].ToString();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Messages WHERE receiver = '" + userLog + "'",
"server=19-20\\sqlexpress;database=mpsip;Integrated Security=SSPI");
DataTable table = new DataTable();
adapter.Fill(table);
Repeater1.DataSource = table;
Repeater1.DataBind();
PagedDataSource pds = new PagedDataSource();
pds.DataSource = table.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 10;
int currentPage;
if (Request.QueryString["page"] != null)
{
currentPage = Int32.Parse(Request.QueryString["page"]);
}
else
{
currentPage = 1;
}
pds.CurrentPageIndex = currentPage - 1;
Label1.Text = "Page " + currentPage + " of " + pds.PageCount;
if (!pds.IsFirstPage)
{
linkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage - 1);
}
if (!pds.IsLastPage)
{
linkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + (currentPage + 1);
}
Repeater1.DataSource = pds;
Repeater1.DataBind();
}
<asp:Repeater ID="Repeater1" runat="server">
<itemtemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<b><%# DataBinder.Eval(Container.DataItem, "title") %></b>
<br>From UserID: <%# DataBinder.Eval(Container.DataItem,
"mlogin", "{0:d}") %>
<br />
Date: <%# DataBinder.Eval(Container.DataItem,
"dateandtime", "{0:d}") %>
<br />
MessageID: <%# DataBinder.Eval(Container.DataItem,
"messageID", "{0:d}") %>
<br />
</itemtemplate>
<separatortemplate>
<hr>
</separatortemplate>
</asp:Repeater>
<br />
<asp:HyperLink ID="linkPrev" runat="server">Previous Page</asp:HyperLink>
<asp:HyperLink ID="linkNext" runat="server">Next Page</asp:HyperLink>
<br />
<asp:Button ID="Button7" runat="server" onclick="Button7_Click"
Text="Button" />
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Compose Message" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Sent Messages" />
</div>
protected void Button7_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI"))
{
conn.Open();
SqlCommand cmdDel = conn.CreateCommand();
SqlTransaction transaction = conn.BeginTransaction("MyTransaction");
cmdDel.Connection = conn;
cmdDel.Transaction = transaction;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
//This assumes data type of messageID is integer, change (int) to the right type
cmdDel.CommandText = "delete from messages where messageID = '" + ((String)((DataRow)Repeater1.Items[i].DataItem)["messageID"]) + "'";
cmdDel.ExecuteNonQuery();
// Continue your code here
}
transaction.Commit();
}
catch (Exception ex)
{
try
{
transaction.Rollback();
}
catch (Exception ex1)
{
//TODO: write log
}
}
}
}
}
There's something wrong with your code, at this line:
mysql = "delete from messages where messageID = '" + CheckBox1.Checked + "'";
It should be:
mysql = "delete from messages where messageID = '" + ((YourClass)Repeater1.Items[i].DataItem).messageID + "'";
And you should use SqlParameter instead of concatenating the String.
Besides, SqlCommand was not executed, you should add this line:
cmdDel.ExecuteNonQuery();
And you must reload data after deleting message.
Besides, you should initialize SqlConnection Object out of the for loop, and use SqlTransaction to manage the transaction.
using (SqlConnection conn = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI"))
{
conn.Open();
SqlCommand cmdDel = conn.CreateCommand();
SqlTransaction transaction = conn.BeginTransaction("MyTransaction");
cmdDel.Connection = conn;
cmdDel.Transaction = transaction;
try {
for (int i = 0; i < Repeater1.Items.Count; i++)
{
//This assumes data type of messageID is integer, change (int) to the right type
cmdDel.CommandText = "delete from messages where messageID = '" + ((int)((DataRow)Repeater1.Items[i].DataItem)["messageID"]) + "'";
cmdDel.ExecuteNonQuery();
// Continue your code here
}
transaction.Commit();
//TODO: reload data here and binding to Repeater
}
catch(Exception ex) {
try {
transaction.Rollback();
}
catch(Exception ex1) {
//TODO: write log
}
}
}
protected void Button7_Click(object sender, EventArgs e)
{
bool BindNeeded = false;
SqlConnection connDelete = new SqlConnection("Data Source=19-20\\sqlexpress;" + "Initial Catalog = mpsip; Integrated Security = SSPI");
connDelete.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)
Repeater1.Items[i].FindControl("CheckBox1");
if (((CheckBox)Repeater1.Items[i].FindControl("CheckBox1")).Checked)
{
//This assumes data type of messageID is integer, change (int) to the right type
CheckBox CheckBox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1");
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("litMessageId");
string messageId = litMessageId.Text;
mySQL = string.Format("delete from messages where messageID = '{0}'", messageId);
SqlCommand cmdDelete = new SqlCommand(mySQL, connDelete);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
if (BindNeeded)
{
Repeater1.DataBind();
}
else
{
Response.Redirect("Messages.aspx");
}
}
catch
{
Response.Redirect("Messages.aspx");
}
}

How to delete a row from DB (*.mdb) in c#

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.

Categories

Resources