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>
Related
I tried to make a message board.
After someone leave message, manager can check message context can be show for others or not.
I use gridView to connect to my SQL Server data, and there is a checkbox in the gridview.
If I checked checkbox, and click "sent" button, SQL Server data will be updated.
If I would like to update checkbox result into SQL Server data, what should I do?
This is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="check or not" SortExpression="replyCheck">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("replyCheck") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("replyCheck") %>' Enabled="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br/>
<asp:Button ID="Button1" runat="server" Text="sent" OnClick="Button1_Click"/>
And this is my aspx.cs - if I use foreach, it can't update into my database
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox reply = (row.Cells[0].FindControl("CheckBox2") as CheckBox);
if (reply.Checked)
{
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
SqlCommand cmd = new SqlCommand($"UPDATE reply SET replyCheck ='1' WHERE (id = {id})", sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.Close ();
DataBind();
}
}
}
If I use for, it showed error about "datakey array"
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
int messageCheck, displayCheck;
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox message = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");
if (message.Checked == true)
{
messageCheck = 1;
SqlCommand cmd1 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd1.ExecuteNonQuery();
}
else
{
messageCheck = 0;
SqlCommand cmd2 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd2.ExecuteNonQuery();
}
}
sqlConnection.Close();
}
Without javascript, how could I do it?
Thanks for you all
Ok, the way this works is that datafields (non templated columns) in the GV use the cells[] collection.
However, for templated columns, we have to use find control.
And also we will use the data keys feature, as that lets us have/use/work with the database PK row ID, but NOT have to display in the markup/grid for users.
Ok, so here is a GV with both datafiles (the cells()), and also check box.
We will select the check boxes, and then with a save button, send changes back to database.
So, our markup:
<div style="width:50%;padding:25px">
<asp:GridView ID="GVHotels" runat="server" class="table borderhide"
AutoGenerateColumns="false" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Smoking" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSmoking" runat="server"
Checked='<%# Eval("Smoking") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Balcony" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkBalcony" runat="server"
Checked='<%# Eval("Balcony") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save changes" CssClass="btn"/>
</div>
And now our code to fill out above could be say this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we see this:
Now, there is two ways we can update the database. We could in fact update using a datatable, and in one whole shot upate the datbase.
but, we just loop the GV, and execute updates. (if I have time, I'll try and post the 2nd more cool approach).
So, our button to update/save changes (for check boxes). Could be this:
protected void cmdSave_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
conn.Open();
string strSQL = "UPDATE tblHotels Set Smoking = #S, Balcony = #B " +
"WHERE ID = #ID";
foreach (GridViewRow gRow in GVHotels.Rows)
{
CheckBox cSmoke = (CheckBox)gRow.FindControl("chkSmoking");
CheckBox cBlacony = (CheckBox)gRow.FindControl("chkBalcony");
int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#S", SqlDbType.Bit).Value = cSmoke.Checked;
cmdSQL.Parameters.Add("#B", SqlDbType.Bit).Value = cBlacony.Checked;
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
cmdSQL.ExecuteNonQuery();
}
}
}
}
Note how we use row index to get the PK row ID. NOTE the DataKeys setting for the GV. This allows you to use/have/enjoy use of the database PK row ID (named "ID" in this code example), and NOT have to display/include the PK in the GV display.
Note that you would continue to use cells() collection for NON templated columns. But for any templated column - you have to use FindControl on that row, pluck out the control, and then you can have at it in regards to that control value.
We could also pull each GV row into a data table, and execute ONE datatable update into the database. But, as the above code shows - we actually keep the connection open for the update - and thus not a big deal either way.
Kindly check with this code
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each row In GridView1.Rows
Dim chk As CheckBox = row.FindControl("CheckBox2")
If chk.Checked Then
'sql update query
Else
End If
Next
End Sub
I'm loading data in a telerik:RadGrid, but I have one column that is not loading, which includes files (binary data).
As you can see in the image, instead of loading DB content, this column just loads System.Byte:
enter image description here
My current bound code is standard
<telerik:GridBoundColumn DataField="FileContent"
FilterControlAltText="Filter por conteudo de ficheiro"
HeaderText="Ficheiro">`
Any ideas on how to load the intended content?
I don't have the telrick gird. But we can display each row, and for each row say have a button on it. When you click on that button, it can downloads that bytes() column from the browser to the client computer.
So, say we have this:
<div style="width:40%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:BoundField DataField="MineType" HeaderText="MineType" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="cmdExcel" runat="server" Height="48px" Width="48px"
ImageUrl="~/Content/excel.png"
OnClick="cmdExcel_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Our database has a column called FileB (byes of the excel file).
So, we can load up the grid, but NOT include the Excel file. But, we did place a button in the grid as per above.
So, code to fill the grid can look like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT ID, FileName, MineType, Description FROM tblFiles";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
}
DataTable MyRst(string strSQL)
{
DataTable rst = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rst.Load(cmdSQL.ExecuteReader());
}
}
return rst;
}
And now we have this:
Note in a above how we not only saved the file name, but ALSO saved the "mine" type. .net 4.5 (or later) has a built in function called GetMineType - you can pass it a file name, and it will produce the correct mine type.
So, in above, when you click on the "image button", then we have this code to fetch the bytes from the database, and send it to the client:
protected void cmdExcel_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gRow = (GridViewRow)btn.Parent.Parent;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// get data from table
DataRow rstData = MyRst("SELECT FileB, FileName, MineType from tblFiles where ID = " + PKID).Rows[0];
Byte[] binFile = (Byte[])rstData["FileB"];
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = rstData["MineType"].ToString();
Response.AddHeader("Content-Disposition", "inline; filename=" + rstData["FileName"]);
Response.BinaryWrite(binFile);
Response.End();
}
As noted, most grids, be they gridview, list view or that telerick grid should work similar. So you don't include the bytes() data in the grid, but allow a button click, and stream down (send) the byte file to the client.
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.
I have the following GridView in which data is being fed from the OleDB Database.
<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server">
<Columns>
...
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
...
</Columns>
</asp:GridView>
And I am reading the contents from the Database and printing in the GridView in the following manner:
protected void ShowGridView()
{
string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string sqlQuery = "select * from ... ";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();
}
What I want to do: I want to append % symbol to the contents of interestRate column in the GridView such that they should be displayed as 3% instead of 3. But the % symbol should not be inserted into the Database. In other words, the % symbol should only be used for display purposes in the GridView.
Depending on how you store the interest rate in the database will depend on which one of the below solutions remedy your question,
If the interest rates are formatted such that 0 = 0% and 1 = 100% you can use:
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" DataFormatString="{0:p}"/>
Documentation
Otherwise you will need to do a template
<columns>
<asp:TemplateField HeaderText="Interest Rate:">
<ItemTemplate>
<asp:Literal ID="IntRate" runat="server" Text='<%# Eval("InterestRate") + "%" %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
</columns>
Updating answer as per comments below
protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
var row = GridViewSavingsTracker.Rows[index];
var interestRate = ((Literal row.FindControl("IntRate")).Text;
if (e.CommandName == "SomeCommand")
{
TextBoxInterestRate.Text = interestRate;
}
}
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