ASP.NET GridView Cell Editing alternative - asp.net

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

Related

ASP.net databound field update value

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.

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>

Problem with asp.net page results

hey guys,
recently while creating a webpage with a gridview, while binding the gridview with sql database, once when i run the site, it shows me the proper results, but when i make any changes and attempt to run the site again, it does not displays the latest changes, instead it displays the results from the previous cache, but when i clears the history, then when i refresh the page, it shows proper results.
Below is my code which i am using to bind my gridview.
SqlConnection con = new SqlConnection(#"[connection string goes here]");
public void FillGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select m.ModuleID, md.FriendlyName from Modules m inner join dbo.ModuleDefinitions md on m.ModuleDefID = md.ModuleDefID", con);
DataTable dt = new DataTable();
adap.Fill(dt);
FunGrid.DataSource = dt;
}
protected void Page_Load(object sender, EventArgs e)
{
FillGrid();
FunGrid.DataBind();
}
Below is the source of the gridview as i am using boundfields to bind gridview.
<form id="form1" runat="server">
<div>
<asp:GridView ID="FunGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" PageSize="10">
<Columns>
<asp:BoundField DataField="ModuleId" HeaderText="Module ID" />
<asp:BoundField DataField="FriendlyName" HeaderText="Module Name" />
</Columns>
</asp:GridView>
</div>
</form>
This is the first time i have got some issues like that, Please if anyone guys have came accross such issues please revert back with the resolutions...
Thanks and Regards
Abbas Electricwala
You can disable caching for the page:
<%# OutputCache Location="None" VaryByParam="None" %>
or add this to your page response:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

Displaying Data in GridView using Dataset

I am trying to display a dataset to my ASP.NET application. It seems that when I click the button event, the data is not displaying in the grid.
I have a basic page with the following:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width="200" Height="300">
</asp:GridView>
<asp:Button runat="server" id="UpdateButton1" onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Then in the code behind, I have the following:
protected void UpdateButton_Click(object sender, EventArgs e)
{
string SQLConfigSettings = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(SQLConfigSettings);
sqlconn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Student", sqlconn);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
UpdatePanel.Update();
}
Am I missing something? Shoudlnt the dataset be diaplayed in the grid?
When I click the button nothing happens.
Thanks :)
You need to add
GridView1.DataBind() right after Gridview1.DataSource.
So it becomes:
...
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
UpdatePanel.Update();
If you need more information about the .DataBind method check MSDN on it
GridView1.DataSource = ds;
Try to mention table inside dataset. Something like ds.Tables[0] or if you know name of table ds.Tables["table_name"]
Put a breakpoint on the first line of code in UpdateButton_Click and run it.
Is that breakpoint reached?
Step through each line of code after that and examine the variable values. Is the DataSet being filled? Can you see the DataTable and its DataRows?
If you reach this event code and have data, then you need to look at the databinding. You need to do GridView.DataBind() immediately after setting the DataSource and before doing the UpdatePanel.Update(). Then you should be good to go.

ASP.Net GridView UpdatePanel Paging Gives Error On Second Click

I'm trying to implement a GridView with paging inside a UpdatePanel. Everything works great when I do my first click. The paging kicks in and the next set of data is loaded quickly. However, when I then try to click a link for another page of data, I get the following error:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 12030
aspx code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<contenttemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="2"
AllowPaging="true" AllowSorting="true" PageSize="20"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_PageSorting"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ActivityLogID" HeaderText="Activity Log ID" SortExpression="ActivityLogID" />
<asp:BoundField DataField="ActivityDate" HeaderText="Activity Date" SortExpression="ActivityDate" />
<asp:BoundField DataField="ntUserID" HeaderText="NTUserID" SortExpression="ntUserID" />
<asp:BoundField DataField="ActivityStatus" HeaderText="Activity Status" SortExpression="ActivityStatus" />
</Columns>
</asp:GridView>
</contenttemplate>
</asp:UpdatePanel>
code behind
private void bindGridView(string sortExp, string sortDir)
{
SqlCommand mySqlCommand = new SqlCommand(sSQL, mySQLconnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
mySqlAdapter.Fill(dtDataTable);
DataView myDataView = new DataView();
myDataView = dt.DefaultView;
if (sortExp != string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
GridView1.DataSource = myDataView;
GridView1.DataBind();
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
protected void GridView1_PageSorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
}
any clues on what is causing the error on the second click?
If anything on your page that is outside UpdatePanel, is changing after the first click, or try to change, on second click is comething diferent, but your calls did get again the fist one value because there are outside UpdatePanel and did not get the update value, just get the first one again -> So product an error on second click.
Probably you have out side the UpdatePanel some data thats need to be rendered correctly.
Keep inside UpdatePanel anything that you change and use with this control.
For example the sSQL, where do you store it ? Its change ? Maybe other value changes on click ?
Probably you have out side the UpdatePanel some data thats need to be rendered correctly. Keep inside UpdatePanel anything that you change and use with this control.

Resources