ASP.net databound field update value - asp.net

I want to update only selected row, but entire rows were updated instead, like this:
before
after
Afterwards, I have tried using #SMT_Assembly for update statement but it give me error "Must declare the scalar variable". I'm new to ASP.net ,please make any necessary modification on my source code and your helps are much appreciated.
Homepage.aspx:
<asp:GridView ID="GridView1" DataKeyNames="SMT_Assembly" AutoGenerateColumns="false" runat="server" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="4" GridLines="Horizontal" Height="214px" Width="848px">
<asp:HyperLinkField DataTextField="IQA_status" NavigateUrl="ConfirmIQAstatus.aspx" HeaderText="IQA status"/>
<asp:HyperLinkField DataTextField="Overall_Status" NavigateUrl="ConfirmIQAstatus.aspx" HeaderText="Overall_Status"/>
</Columns>
</asp:GridView>
Homepage.cs
public partial class Homepage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(#"Data Source=MYPENM0LSQLV01D\INST3;Initial Catalog=RTDF;Persist Security Info=True;User ID=*******; Password=*******");
String query = "UPDATE RTDF.dbo.SMT_CompWeight SET IQA_status = 'Open' where SMT_Assembly = #SMT_Assembly ";
SqlCommand retrieveCommand = new SqlCommand(query,sqlcon);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = retrieveCommand;
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
sqlcon.Close();
}
}

Selecting the row event is fired when you make a click on the select link. If you need any particular item in that row you can easily select it using the cells property. In the Gridview, double-Click on the SelectedIndexChanged Event and write the following code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBoxUserID.Text = GridView1.SelectedRow.Cells[1].Text;
TextBoxUserName.Text = GridView1.SelectedRow.Cells[2].Text;
}
Source: https://www.c-sharpcorner.com/UploadFile/rohatash/how-to-get-the-selected-row-in-gridview-using-Asp-Net/
EDIT:
and I think for your grid you should add AutoGenerateSelectButton="True"
and if that doesn't work, try: OnSelectedIndexChanged="function" or onitemcommand="function"
it seems very similar to Telerik:RadGrid that I'm familiar with.

Related

how to change the gridview row value after button click event

I have a table in four columns see screenshot here:
But I need two columns in that table name and gender see screenshot here:
Display in this type but I have required after click the button row value will change in GridView button out side in GridView e.g. row value 1,2 can instead male and female that is my requirement.
You need to fetch that data from database in dataset or datatable and assign that as DataSource to the GridView and call DataBind on that GridView. Now in RowDataBound event compare the value and assign value to UI label / literal based on that.
Below is GridView in aspx page.
<asp:GridView runat="server" AutoGenerateColumns="false" ID="GridView1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:Literal ID="ltrlEmpName" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Gender">
<ItemTemplate>
<asp:Literal ID="ltrlEmpGender" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In code behind, lets say you want to assign the datasource to this GridView in page load or any other method. Below will be its code. Note that in sample here I have taken dummy DataTable and filled values for simplicity, you need to fill that DataTable from db values.
protected void Page_Load(object sender, EventArgs e)
{
// Dummy data table below, that needs to be replaced by datatable / dataset fetched from database.
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpName", typeof(string)));
dt.Columns.Add(new DataColumn("EmpGender", typeof(int)));
DataRow dr1 = dt.NewRow();
dr1["EmpName"] = "Romesh";
dr1["EmpGender"] = 1;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["EmpName"] = "Sandya";
dr2["EmpGender"] = 2;
dt.Rows.Add(dr2);
// Bind the datasource to gridview.
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
System.Web.UI.WebControls.Literal ltrlEmpName = (System.Web.UI.WebControls.Literal)e.Row.FindControl("ltrlEmpName");
System.Web.UI.WebControls.Literal ltrlEmpGender = (System.Web.UI.WebControls.Literal)e.Row.FindControl("ltrlEmpGender");
// Bind employee name to its label.
ltrlEmpName.Text = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "EmpName"));
// Bind employee gender to its label based on its value.
if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "EmpGender")) == "1")
{
ltrlEmpGender.Text = "Male";
}
else if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "EmpGender")) == "2")
{
ltrlEmpGender.Text = "Female";
}
else
{
ltrlEmpGender.Text = "Other";
}
}
}
You will get out as Table as below.

Putting data from SQL query into grid view asp.net

I have a grid box in which I want to fill data from a database where the username is one and their location was added in the last 24 hours.
I have tested the SQL query and it is working fine, however when trying to put the data in a grid box nothing happens.
Here is the code I have used in the aspx.cs file:
public partial class last24hours : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source = sql2008.net.dcs.hull.ac.uk; Initial Catalog = rde_514872; Integrated Security = True");
protected void Page_Load(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Location FROM StaffLocation WHERE [Date and Time]>= getdate()-1 AND [Username] = '1'";
cmd.Connection = con;
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
gridView1 is an empty grid view I have made with no sql source.
This is how the gridview is initialised in the aspx file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
You have AutoGenerateColumns set to false. And since you haven't defined any columns manually, of course nothing is going to show up. There's two fixes:
Set auto generate columns to true.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" />
Or manually define your columns
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
</Columns>
</asp:GridView>

How to put GridView into edit mode while nested in two Repeaters?

I have a Gridview inside a Repeater inside another Repeater. The declarative code looks like this:
<asp:Repeater id="parentRepeater" runat="server">
<itemtemplate>
<b> <%# DataBinder.Eval(Container.DataItem, "Name") %></b>
<div>
<asp:repeater id="childRepeater" runat="server" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' OnItemDataBound="getNestedData">
<itemtemplate>
<div><%# DataBinder.Eval(Container.DataItem, "Owner") %></div>
<div><asp:GridView ID="Grd" runat="server" AutoGenerateColumns="false" OnRowEditing="EditRecord" HorizontalAlign="Left" Width="100%">
</asp:GridView></div>
</itemtemplate>
</asp:repeater>
</div>
</itemtemplate>
</asp:repeater>
The imperative code-behind looks like this:
public void Page_Load(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection("asdf");
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from tblNames", cnn);
DataSet ds = new DataSet();
cmd1.Fill(ds, "names");
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from tblThings", cnn);
cmd2.Fill(ds, "things");
ds.Relations.Add("myrelation",
ds.Tables["names"].Columns["id"],
ds.Tables["things"].Columns[NameID"]);
parentRepeater.DataSource = ds.Tables["names"];
Page.DataBind();
cnn.Close();
}
So that will set up the parent repeater, and the child repeater, and when the child repeater has an itemdatabound, the following happens which binds the gridview:
public void getNestedData(Object Sender, RepeaterItemEventArgs e)
{
GridView subGridView = (GridView)e.Item.FindControl("Grd");
DataRow rowView = (DataRow)e.Item.DataItem;
Int32 key = (Int32)rowView["id"];
SqlConnection cnn = new SqlConnection("asdf");
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from tblSubThings WHERE ThingID = " + key, cnn);
DataSet ds = new DataSet();
cmd1.Fill(ds, "subThings");
subGridView.DataSource = ds.Tables["subThings"];
TemplateField edit = new TemplateField();
edit.ItemTemplate = new editGridViewTemplate(DataControlRowType.DataRow, "edit");
subGridView.Columns.Add(edit);
TemplateField Notes = new TemplateField();
Notes.ItemTemplate = new GridViewTemplate3(DataControlRowType.DataRow, "Notes");
Notes.HeaderTemplate = new GridViewTemplate3(DataControlRowType.Header, "Notes");
Notes.EditItemTemplate = new NotesEditGridViewTemplate(DataControlRowType.DataRow, "Notes");
subGridView.Columns.Add(Notes);
subGridView.DataBind();
}
This code all works fine. It shows gridview inside two repeaters, with an edit button. And when the edit button is fired, the gridview is supposed to go into edit mode (and use the EditItemTemplate). However, the gridview does not go into editmode when EditRecord is called. This is what EditRecord looks like:
public void EditRecord(object sender, GridViewEditEventArgs e)
{
GridView subGridView = (GridView)sender;
subGridView.EditIndex = e.NewEditIndex;
subGridView.Rows[e.NewEditIndex].RowState = DataControlRowState.Edit;
DataBind();
}
Does anyone know how I can get my GridView into edit mode?

ASP.NET GridView Cell Editing alternative

Is it possible to edit and update a GridView cell without using
<asp:TemplateField> and/or
<%# Eval("Name") %> and/or
<%# Bind("Name") %> and/or
SqlDataSource ?
NB : I want to use only C# code in the behind and SqlConnection, SqlCommand, ExecuteXXX, etc.
NB : Plz provide me code(C# and aspx) or a web-link containing code.
Use onrowediting and onrowupdating in gridview markup...
something like this:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AllowPaging="true" AllowSorting="true" PageSize="5" DataKeyNames="Id"
onpageindexchanging="GridView1_PageIndexChanging"
AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
onsorting="GridView1_Sorting" onrowediting="GridView1_RowEditing">
I am not very sure about winforms, but in websites try this..
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//your code that will edit/update.
}
In general, code with Sqlcommand and Sqlconnection will be something like:
SqlConnection con;
SqlCommand cmd;
DataSet ds;
SqlDataAdapter da;
protected DataSet FillDataSet()
{
string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
con = new SqlConnection(source);
cmd = new SqlCommand("proc_mygrid", con);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
return ds;
}
Hope this helps.
I still don't figure out why are you fighting against asp.net, but you can do what you want using ObjectDataSource. The ObjectDataSource control uses reflection to call methods of a business object to select, update, insert, and delete data. You set the ObjectDataSource control's TypeName property to specify the name of the class to use as a source object.
Working with ObjectDataSource resume to do things like:
To Declare it:
<asp:objectdatasource
runat="server"
id="ObjectDataSource1"
typename="EmployeeLogic"
selectmethod="GetAllEmployees"
updatemethod="UpdateEmployeeInfo"
dataobjecttypename="NorthwindEmployee" />
To Create Methods into code-behind:
public List<NorthwindEmployee>GetAllEmployees()
{
//your code here
}
public void UpdateEmployeeInfo(NorthwindEmployee emp) {
//your code here
}
to Configure the GridView and to be happy :)
Below I've provided some links that might help you:
http://www.manuelabadia.com/blog/PermaLink,guid,c72852ae-1fdd-4934-a715-f565ceaf21cc.aspx
http://msdn.microsoft.com/en-us/library/57hkzhy5.aspx
http://www.google.com.br/search?hl=en-us&q=objectdatasource+asp.net
A possible solution maybe is to manage the RowDataBound event of the gridview and set the values like
e.Row.Cells(i).Text = value

Need help in radiobutton within gridview

Thru radio button i am selecting the data from gridview. Here all radio buttons are selectable at a time. Actually it should not happen at a time user can select only one button which i could not do. My second problem is when i am selecting particular radiobutton that details should be displayed in text box. I have Itemid, ItemName, Quantity, Rate and Total field in gridview. These values i have inserted thru textbox so i have all the corresponding text box for all. So once i select particular radiobutton those details should be displayed in corresponding textbox. I have done the insertion coding for this but couldn't do selecting thru radiobutton and dispalying in textbox. Pls somebody help me in coding for this problem.
Thanks,
sumit
Sumit,
Don't use the html control, use the asp control:
<asp:RadioButton ID="RadioSelector" runat="server" GroupName="RadioSelectors" />
I had a similar problem in an ASP.NET class, and I followed this tutorial which worked perfectly.
Sounds like the classic master/detail pattern see here:
Tutorial 10: Master/Detail Using a Selectable Master GridView with a Details DetailView
You are fighting the intended workings of ASP.NET databound controls by using radio buttons. I don't like having select links either they're not exactly Web 2.0! but they can be quite easily replaced with a row click by doing this (or variation of same):
Select a row in an asp:GridView without using a Select Command
I read several articles on the net but none were suitable. I finally figured out my own solution without using either HTMLControls radiobutton nor using Javascript. This works for my requirement.
My Gridview html settings were as follows
<asp:GridView ID="grdVersion" runat="server"
AutoGenerateColumns="false" AllowPaging="true"
AutoGenerateEditButton="false" PageSize="10" Width="400px"
EmptyDataText="No records available."
OnRowDataBound="grdVersion_RowDataBound"
AutoGenerateSelectButton="false">
<Columns>
<asp:BoundField DataField="versionid" HeaderText="Version No." ItemStyle-Width="50px"
ItemStyle-Wrap="false" HtmlEncode="true" ReadOnly="true" />
<asp:BoundField DataField="version_date" HeaderText="Version Date" ItemStyle-Width="100px"
ItemStyle-Wrap="false" HtmlEncode="true" ReadOnly="true" />
<asp:BoundField DataField="remarks" HeaderText="Remarks" ItemStyle-Width="150px"
ItemStyle-Wrap="true" HtmlEncode="true" ReadOnly="true" />
**<asp:TemplateField HeaderText="Admin" HeaderStyle-Width="100px">
<ItemTemplate>
<asp:RadioButton ID="rdCurrent" runat="server"
Checked="false" Enabled="true" GroupName="rgVersion"
AutoPostBack="true"
OnCheckedChanged="rdCurrent_CheckChanged" />
</ItemTemplate>**
</asp:TemplateField>
</Columns>
</asp:GridView>
The server code (C#) was as follows,
DataTable dtDataSpaceVersions; //place this inside the codebehind page class
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dtDataSpaceVersions = ListDataSpaceVersions();
ViewState["dtDataSpaceVersions"] = dtDataSpaceVersions;
PopulateGridVersion();
}
}
protected void PopulateGridVersion()
{
grdVersion.DataSource = dtDataSpaceVersions;
grdVersion.DataBind();
}
protected void rdCurrent_CheckChanged(object sender, EventArgs e)
{
Control selectedVersion = ((Control)sender).Parent;
if (ViewState["dtDataSpaceVersions"] != null)
dtDataSpaceVersions = (DataTable)ViewState["dtDataSpaceVersions"];
foreach (DataRow dtr in dtDataSpaceVersions.Rows)
{
if (dtr["versionid"].ToString() == ((System.Web.UI.WebControls.GridViewRow)selectedVersion.Parent).Cells[0].Text)
dtr[3] = "Y";
else
dtr[3] = "N";
}
PopulateGridVersion();
}
protected void grdVersion_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv;
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
{
drv = (DataRowView)e.Row.DataItem;
if ((RadioButton)(e.Row.FindControl("rdCurrent")) != null)
if (drv.Row.ItemArray[3].ToString() == YesNo.N.ToString())
((RadioButton)(e.Row.FindControl("rdCurrent"))).Checked = false;
else
((RadioButton)(e.Row.FindControl("rdCurrent"))).Checked = true;
//setGridUserPermissionCheckBoxState(e.Row, drv);
}
}
public DataTable ListDataSpaceVersions()
{
string sql = string.Empty;
DataTable dt = new DataTable();
dt.Columns.Add("versionid", typeof(String));
dt.Columns.Add("version_date", typeof(String));
dt.Columns.Add("remarks", typeof(String));
dt.Columns.Add("is_current", typeof(String));
DataRow dtr;
dtr = dt.NewRow();
dtr[0] = "1.1";
dtr[1] = "12-Dec-2005";
dtr[2] = "Campaign Information";
dtr[3] = "N";
dt.Rows.Add(dtr);
dtr = dt.NewRow();
dtr[0] = "1.2";
dtr[1] = "06-Mar-2006";
dtr[2] = "Sales corrections";
dtr[3] = "N";
dt.Rows.Add(dtr);
dtr = dt.NewRow();
dtr[0] = "1.3";
dtr[1] = "24-Aug-2009";
dtr[2] = "Invoice reconciliation";
dtr[3] = "Y";
dt.Rows.Add(dtr);
dtr = dt.NewRow();
dtr[0] = "1.4";
dtr[1] = "30-May-2010";
dtr[2] = "Invoices verification";
dtr[3] = "N";
//dtr[0][0] = "";
dt.Rows.Add(dtr);
return dt;
}

Resources