Not able to access the ID while deleting the row from GridView - asp.net

I am using a Gridview containing an ID. I want to write a Row_deleting event in which I access the ID from my .aspx page, but I am not getting it.
How can I do that?
Here is my Gridview Code
<asp:LinkButton ID="lnkDelete"
runat="server" CssClass="gridLink"
CommandArgument='<%# Eval("Serial_key") %>'
CommandName="Delete">
<b>Delete</b>
</asp:LinkButton>

first in your gridview set AutoGenerateDeletebutton=true then use this link
How to use the GridView AutoGenerateDeletebutton
protected void DeleteRowButton_Click(Object sender, GridViewDeleteEventArgs e)
{
var PN = GridView1.DataKeys[e.RowIndex].Values["Part_Number"];// this is how you get the right row to delete e.rowindex is used to do this
string PN = pn.ToString;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
con.Open();
string str = "DELETE * FROM XML WHERE ([Part_Numbber] = " + PN + ")";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Button1_Click(sender, e);
con.Close();
}

For Deleting any record from your database you need unique or Primary key column. If you want to delete record using column "Serial_key" . Then put the following code to Delete.
<ItemTemplate>
<asp:Label ID="lblSerial_key" runat="server" Text='<%# Eval("Serial_key") %>'></asp:Label>
<asp:Button ID="deleteButton" runat="server" CommandName="Delete" Text="Delete" /></ItemTemplate>
Now you can use the lblSerial_key to delete a row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string Serial_key = string.Empty;
Label lblId = (Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblSerial_key");
Serial_key = lblId.Text.ToString();
string selectSQL = "delete from tablename where id='" + Serial_key + "'";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
// Create the command object
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL , con);
cmd.ExecuteNonQuery();
con.Close();
}

Related

method of populate dropdownlist inside gridview

If i want to populate a DropdownList in a GridView what will be the best way? use GridView 'OnRowDataBound' event and fetch query everytime to db or get all data first and put it on datatable and do further work from this datatable ?
As your question is unclear about your requirement, I assume that you want to bind dropdownlist inside the Gridview using OnRowDataBound event of gridview.
So here are the steps:-
Add a Gridview HTML in your aspx page with DropDownList in ItemTemplate of TemplateField.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField HeaderText="Name" DataField="ContactName" />
<asp:TemplateField HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' Visible = "false" />
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you need to bind the gridview with records which will come from the database.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT ContactName, Country FROM Customers");
GridView1.DataBind();
}
}
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
Then the code for OnRowDataBound will follow like below :-
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}
See the Reference link for your reference
Also see the Working demo for your reference
Hope that helps.

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'name'

Asp.code
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged1" DataTextField="socialname">
<asp:ListItem text="select">Comment using</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:prakashConnectionString %>" SelectCommand="SELECT [socialname] FROM [socialnetwork]"></asp:SqlDataSource>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
C# code
SqlConnection con = new SqlConnection("****");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindddl();
BindTitle();
Label3.Text = DropDownList1.Items[0].Text;
}
}
protected void Bindddl()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from socialnetwork", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = "socialname";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
con.Close();
}
protected void BindTitle()
{
if (DropDownList1 != null)
{
foreach (ListItem li in DropDownList1.Items)
{
li.Attributes["title"] = "social/" + li.Value; // it ll set the value of items in dropdownlist as tooltip
}
}
}
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
BindTitle();
Label3.Text = DropDownList1.SelectedItem.Text;
Label3.Text = "Commented by";
}
You have not assigned the DataSource:
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "socialname";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
But you have used both, the DataSourceID on the aspx and the codebehind DataSet. For the SqlDataSource you have not selected the name but only:
SELECT [socialname] FROM [socialnetwork]
Just remove the SqlDataSource, it is simply redundant.
As an aside, i suggest to use the using-statement for the connection and the dataadapter to ensure that all unmanaged resources are disposed and the connection gets closed (even on error):
DataSet ds = new DataSet();
using(SqlConnection con = new SqlConnection("****"))
using(SqlDataAdapter da = new SqlDataAdapter("select * from socialnetwork", con))
da.Fill(ds); // you don't need to open/close the connection with Fill
DropDownList1.DataSource = ds.Tables[0];
// ...
I ran into a similar issue using an asp.net listbox. I changed the name of the column I was returning into the display value field to match the name in the error condition and that resolved the issue. For example I was getting this error:
[HttpException (0x80004005): DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'DisplayValue'.]
The value that was being returned from my SELECT statement was held in a column named theValue. I changed the column alias to be DisplayValue instead:
SELECT theValue as DisplayValue
FROM whateverTable
note I am working in VS 2012.

bind image from database to datalist

I am binding image to datalist.
My imagename is in database, i am taking it and wants to bind it to datalist.
I have tried following:
<asp:DataList ID="dlImages" runat="server">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px"
ImageUrl='<%# Bind ("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}") %>' runat="server" />
</ItemTemplate>
</asp:DataList>
on pageload i have bounded it as:
ds = gc.GetDataToListBinder("select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID")
dlImages.DataSource = ds.Tables(0)
dlImages.DataBind()
In above code ds is my dataset and gc.GetDataToListBinder(query) returns dataset.
But images are not getting displayed.
What can be the mistake?
EDIT1:
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px" ImageUrl='<%#Server.HtmlDecode(Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg")) %>' runat="server" />
Take a minute and read this:
http://www.codeproject.com/Articles/142013/There-is-something-about-Paths-for-Asp-net-beginne
I think this will help you alot.
EDIT:
For the space problem, take a look:
Why does HttpUtility.UrlEncode(HttpUtility.UrlDecode("%20")) return + instead of %20?
Basically:
ImageUrl='<%# Server.HtmlDecode(Bind("MyImage")) %>'
But i recommend that you store your image name without space in db.
EDIT2:
ImageUrl='<%# Eval("MyImage") %>'
ImageUrl='<%# Server.HtmlDecode(Eval("MyImage")) %>'
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal" CellPadding="2"
CellSpacing="2"
UseAccessibleHeader="True" >
<ItemTemplate>
<asp:ImageButton Width="120" Height="120" ID="Image1" ImageUrl='<%# Eval("Imgpath", "") %>' runat="server" />
</asp:Datalist>
.CS
SqlConnection con;
SqlCommand cmd;
string strCon = "Connection String";
SqlDataAdapter da;
protected void AlldataImg()
{
DataTable dt = new DataTable();
string strQuery = "select code,imgpath from SA_Stock order by Code";
cmd = new SqlCommand(strQuery);
con = new SqlConnection(strCon);
da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
da.SelectCommand = cmd;
da.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
da.Dispose();
con.Dispose();
}
}
protected void Page_Load(object sender, EventArgs e)
{
AlldataImg();
}
Put Image Path in database too so that image will appear..
protected void DataListPosts_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView dr = (DataRowView)e.Item.DataItem;
Image ImageData = (Image)e.Item.FindControl("ImageData");
if (dr.Row[4].ToString() != "NA")
{
ImageData.Visible = true;
ImageData.ImageUrl = #"ImgPost/" + dr.Row["ImgPath"].ToString();
}
else
ImageData.Visible = false;
}
}
catch (Exception)
{ }
}
its a old topic but i think it can be usefull for anyone
firstly get your data from string
string sqlget = "select Photo from Promoter";
and get it to database dsget
then do that
dsget.Tables[0].Columns.Add("Photopath", typeof(string));
for (int i = 0; i < dsget.Tables[0].Rows.Count; i++)
{
if (dsget.Tables[0].Rows[i]["Photo"].ToString() != null && dsget.Tables[0].Rows[i]["Photo"].ToString() != "")
{
var data = (Byte[])(dsget.Tables[0].Rows[i]["Photo"]);
var stream = new MemoryStream(data);
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
FileBytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(FileBytes, 0, FileBytes.Length);
dsget.Tables[0].Rows[i]["Photopath"] = "data:image/png;base64," + base64String;
}
}
DataList1.DataSource = dsget.Tables[0];
DataList1.DataBind();
in asp file write the following thing

How to refresh Gridview after pressed a button in asp.net

I am trying to make a simple library database. I list the search results in a gridview, then i have a textbox and a button, user enters the isbn and clicks loan button. Then, if there is enough number of items (itemNumber>0) it is loaned by user. Here is the screenshot of user interface:
My question is, when user clicks loan button the loan may or may not be succesful. In both cases, i print a message indicating whether loan is succesful or not, and i also want the updated gridview to be displayed. The problem is, after pressing the loan button the gridview disappears and i just see the textbox, button and the message on the screen. How can i show the updated version of gridview after pressing loan button?
Here is the code file:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchResults.aspx.cs" Inherits="Pages_SearchResults" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ISBN" DataSourceID="SqlDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="ISBN" HeaderText="ISBN" ReadOnly="True"
SortExpression="ISBN" />
<asp:BoundField DataField="AuthorName" HeaderText="AuthorName"
SortExpression="AuthorName" />
<asp:BoundField DataField="AuthorlName" HeaderText="AuthorlName"
SortExpression="AuthorlName" />
<asp:BoundField DataField="ItemType" HeaderText="ItemType"
SortExpression="ItemType" />
<asp:BoundField DataField="PublishYear" HeaderText="PublishYear"
SortExpression="PublishYear" />
<asp:BoundField DataField="numOfCopies" HeaderText="Number of Copies"
SortExpression="numOfCopies" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Items] WHERE ([Title] LIKE '%' + #Title + '%')">
<SelectParameters>
<asp:FormParameter FormField="tSearchBox" Name="Title" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server" Text="Type ISBN to loan:"></asp:Label>
And here is the .cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Pages_SearchResults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
Int32 verify;
string title = GridView1.HeaderRow.Cells[0].Text, isbn = GridView1.HeaderRow.Cells[1].Text, name = GridView1.HeaderRow.Cells[2].Text, lname = GridView1.HeaderRow.Cells[3].Text, type = GridView1.HeaderRow.Cells[4].Text, year = GridView1.HeaderRow.Cells[5].Text;
}
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
string numQuery = "select numOfCopies from Items where ISBN='" + tLoanBox.Text + "'";
SqlCommand cmdnumQuery = new SqlCommand(numQuery, con);
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
int num=Convert.ToInt32(cmdnumQuery.ExecuteScalar());
result = cmd2.ExecuteNonQuery();
if (num > 0)
{
if (result > 0)
Response.Redirect("LoanSuccesfull.aspx");
}
else
notAvailable.Visible = true;
con.Close();
}
}
And here is the code for loan button:
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
result = cmd2.ExecuteNonQuery();
if (result > 0)
{
loanSuccesful.Visible = true;
Response.Redirect("LoanSuccesfull.aspx");
}
con.Close();
}
I appreciate any help. Thanks
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
I was totally lost on why my Gridview.Databind() would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :
gvTypes.EditIndex = -1;
gvTypes.DataBind();
gvTypes is my GridView ID.
Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.
Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
GridView1.DataBind()
End Sub

int data type is not working as parameter

I have a GridView in which I have check box as Item Template, and I am updating the GridView when check box is changed. Here is my GridView code:
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="chkcelar" runat="server" Text="Clear" OnCheckedChanged="chkclearchng" AutoPostBack="true"/>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="BPV_NUM" DataType="System.Int64"
DefaultInsertValue="" HeaderText="BPV No" SortExpression="BPV_NUM"
UniqueName="BPV_NUM">
</telerik:GridBoundColumn>
</Columns>
and here is the c# code through which I am updating grid view
protected void chkclearchng(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle");
OleDbCommand cmd = new OleDbCommand();
CheckBox chkcelar = ((CheckBox)(sender));
GridDataItem row = ((GridDataItem)(chkcelar.NamingContainer));
long bpvnum = row.Cells[1].Text;
if (chkcelar.Checked ) {
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=1, CLR_DTE=sysdate where bpv_num=:bpv_num and bpv_dte=:bpv_dte";
}
else {
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=0, CLR_DTE=sysdate where bpv_num=:bpv_num and bpv_dte=:bpv_dte";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.Add(":bpv_num",OleDbType.BigInt).Value = bpvnum;
cmd.Parameters.Add(":bpv_dte",OleDbType.Date).Value = RadComboBox1.SelectedValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The problem is that when I change the check box this error appears:
Input string was not in a correct format.
Can anyone tell what may be the issue and how can I resolve it?
Change your code like this:
protected void chkclearchng(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle"))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand(null, con))
{
CheckBox chkcelar = ((CheckBox)(sender));
GridDataItem row = ((GridDataItem)(chkcelar.NamingContainer));
long bpvnum = Convert.ToInt64(row.Cells[1].Text);
if (chkcelar.Checked)
{
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=1, CLR_DTE=sysdate where bpv_num=#bpv_num and bpv_dte=#bpv_dte";
}
else
{
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=0, CLR_DTE=sysdate where bpv_num=#bpv_num and bpv_dte=#bpv_dte";
}
cmd.Parameters.Add(new OleDbParameter("#bpv_num", bpvnum));
cmd.Parameters.Add(new OleDbParameter("#bpv_dte", Convert.ToDateTime(RadComboBox1.SelectedValue)));
cmd.ExecuteNonQuery();
}
}
}
May be you should use
long bpvnum = long.Parse(row.Cells[1].Text);
if doesn'T work then on this line
cmd.Parameters.Add(":bpv_dte",OleDbType.Date).Value = RadComboBox1.SelectedValue
You need parameter type OleDbType.Date but you are assigning RadComboBox1.SelectedValue
so you need to convert your
RadComboBox1.SelectedValue to OleDbType.Date
or you should simply use DateTimePicker
instead of ComboBox
Using Quick window check what is the vaule returns on "row.Cells[1].Text".
The issue in your code is because of the wrong type conversion from "string" to "OleDbType.Date". So replace the following code
cmd.Parameters.Add(":bpv_dte",OleDbType.Date).Value = RadComboBox1.SelectedValue;
with the following code
cmd.Parameters.Add(New OleDb.OleDbParameter("#bpv_dte", OleDb.OleDbType.Date));
cmd.Parameters("#bpv_dte").Value = RadComboBox1.SelectedValue.ToString("d");
Also make sure to convert all types correctly to OleDbType if there are more lines used for insertion.

Resources