Below is my UI and Table. I wanted to insert image of a child inside the gridview, which will be saved in the database as well. Please assist how i suppose to achieve this.
Datatype for image on table is varchar(MAX).
here is what i have done so far.
(C# Code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace MyProject
{
public partial class managechild : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["lolConnectionString1"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
string session = System.Web.HttpContext.Current.User.Identity.Name;
Response.Cookies["uname"].Value = session;
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "SELECT * from child c join parent p on c.ParentId = p.ParentId join login l on l.Username = p.UserId where l.Username ='" + session + "'";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
gvUpload.DataSource = ds;
gvUpload.DataBind();
conn.Close();
}
protected void btnUpload_OnClick(object sender, EventArgs e)
{
TextBox txtName = (TextBox)gvUpload.SelectedRow.FindControl("ChildName");
FileUpload fuploadFile = (FileUpload)gvUpload.SelectedRow.FindControl("fUpload");
Button btnUpload = (Button)gvUpload.SelectedRow.FindControl("btnUpload");
if (fuploadFile.HasFile)
{
string fileName = fuploadFile.FileName;
string exten = Path.GetExtension(fileName);
//here we have to restrict file type
exten = exten.ToLower();
string[] acceptedFileTypes = new string[4];
acceptedFileTypes[0] = ".jpg";
acceptedFileTypes[1] = ".jpeg";
acceptedFileTypes[2] = ".gif";
acceptedFileTypes[3] = ".png";
bool acceptFile = false;
for (int i = 0; i <= 3; i++)
{
if (exten == acceptedFileTypes[i])
{
acceptFile = true;
}
}
if (!acceptFile)
{
lblMsg.Text = "The file you are trying to upload is not a permitted file type!";
}
else
{
//upload the file onto the server
fuploadFile.SaveAs(Server.MapPath("~/images/child/"+fileName));
conn.Open();
string cmdstr = "insert into Child (Image) values (#photo)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#photo", "images/child/"+fileName);
cmd.ExecuteNonQuery();
conn.Close();
BindGrid();
}
}
}
}
}
UI Code (asp.net)
<asp:GridView ID="gvUpload" runat="server" AutoGenerateColumns="False"
ShowFooter="True" CellPadding="4" ForeColor="#333333" GridLines="None"
style="margin-left: 128px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Child Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#DataBinder.
Eval(Container.DataItem, "ChildName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="imgPhoto" runat="server" Width="100px" Height="120px"
ImageUrl='<%#DataBinder.Eval(Container.DataItem, "Image") %>' />
</ItemTemplate>
<ItemTemplate>
<asp:FileUpload ID="fUpload" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_OnClick" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
When posting on SO pls make sure to show at least some attempt to solve the problem yourself before asking others for complete solution.
One way is to save image in database as binary data in which case you'll need to add varbinary column to your table.
Another way is to only save the path to the image and save the image in some folder on the server.
If you don't have a lot of images I'd suggest you go with the second solution as it will be easier to implement. Just look up how to upload image file and you'll be on the right track.
Related
I have a dropdownlist that is populated by the names of the tables in the database. Then when the admin chooses or clicks a table name. The gridview below is populated by the data in the table. The admin should be able to edit, update, delete and select. However the commands supplied by the gridview are not working. When you click edit it does not execute. Then when you click select it deletes. The commands have a mix up somewhere. So l changed the commands into templates so l can code them myself. However the solutions l found online do not work. Because one
The Gridview does not only show data from one table but multiple so l cannot be specific in my query that l want delete the row of a certain table but just say l want to delete the row of the table showing. This goes for all the other events
Code for like editing GridView1.EditIndex = e.NewEditIndex does not work. It displays a
System.EventArgs error. NewEditIndex has no extension method and is
not accepting a first argument of type System.EventArgs could be
found.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings ["tlcString"].ConnectionString);
protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e)
{
con.Open ();
//Populates the gridview with the selectedindex in the list. The selectedindex being the table
SqlDataAdapter da = new SqlDataAdapter(string.Format ("Select * From {0}", drpTable.SelectedValue), con);
DataSet ds = new DataSet ();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds. Tables [0];
GridView1.DataBind ();
con.Close ();
}
private void BindData ()
{
//Binds the data in the gridview with the database table and updating it if changes are ever made. The method is called.
string strQuery = "Select * From {0}";
SqlCommand cmd = new SqlCommand (strQuery);
GridView1.DataSource = GetData (cmd);
GridView1.DataBind ();
}
private object GetData (SqlCommand cmd)
{
throw new NotImplentedException ();
}
//this is the code for the commads after l turned them into templatefields. But l only wrote code for the edit button only. It would be appreaciated if code for the other commands is supplied
protected void LinkButton1_Click (object sender, EventArgs e)
{
//Set edit index
GridView1.EditIndex = e.NewEditIndex;
BindData ();
}
//THATS all my code. The commands that were acting up were auto generated in the gridview properties window.
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server"
CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Select" Text="Select"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center"
/>
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333"
/>
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" /></asp:GridView>
I want to export ONLY the search results to an excel spreadsheet, but for whatever reason I am missing, I am exporting all of the database table instead. Please help!
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace Inventory.pages
{
public partial class view : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Equipment"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Equipment ORDER by BLDG", conn);
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
DA.Fill(ds);
View_Results.DataSource = ds;
View_Results.DataBind();
conn.Close();
}
public void search()
{
string sqlQuery = "SELECT *" +
"FROM Equipment WHERE " +
"[Description] LIKE #SEARCH OR [Manufacturer] LIKE #SEARCH OR [MODEL_NO] LIKE #SEARCH " +
"OR [SERIAL_NO] LIKE #SEARCH OR [GROUP] LIKE #SEARCH " +
"OR [BLDG] LIKE #SEARCH OR [Room] LIKE #SEARCH OR [FIRST] LIKE #SEARCH " +
"OR [LAST] LIKE #SEARCH OR [INSTALLED] LIKE #SEARCH " +
"OR [GROUP] LIKE #SEARCH";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.Add(new SqlParameter("#SEARCH", "%" + SearchBox.Text + "%"));
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
DA.Fill(ds);
View_Results.DataSource = ds;
View_Results.DataBind();
conn.Close();
}
protected void Search_Click(object sender, EventArgs e)
{
search();
}
protected void Download_Results_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=EquipmentQuery.xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
View_Results.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
}
}
<%# Page Title="" Language="C#" MasterPageFile="~/pages/withoutsidebar.Master" AutoEventWireup="true" CodeBehind="view.aspx.cs" Inherits="Inventory.pages.view" %>
<asp:Content ID="Content" ContentPlaceHolderID="Content" runat="server">
<asp:TextBox ID="SearchBox" runat="server" CssClass="ViewSearch" Font-Italic="True" Font-Names="Arial" Font-Size="11px" ForeColor="#333333" Height="19px" TextMode="Search" Width="220px">Search here...</asp:TextBox>
<asp:Button ID="Search" runat="server" Height="25px" OnClick="Search_Click" Text="Search" Width="100px" Font-Size="11px" />
<asp:Button ID="Download_Results" runat="server" Font-Size="11px" Height="25px" OnClick="Download_Results_Click" Text="Download Results" />
<br />
<br />
<asp:GridView CssClass="View_Grid" ID="View_Results" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" CellPadding="2" RowStyle-Width="20px" AlternatingRowStyle-BackColor="#99ccff">
<Columns>
<asp:BoundField HeaderText="PROPERTY NUMBER" DataField="PROP_NO" ControlStyle-CssClass="PROP_NO" >
<ControlStyle BorderWidth="1px" Height="10px" Width="35px" />
</asp:BoundField>
<asp:BoundField HeaderText="MANUFACTURER" DataField="Manufacturer" ControlStyle-CssClass="MANUFACTURER" >
<ControlStyle BorderWidth="1px" Height="20px" Width="35px" />
</asp:BoundField>
<asp:BoundField HeaderText="DESCRIPTION" DataField="DESCRIPTION" ControlStyle-CssClass="DESCRIPTION" >
<ControlStyle BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField HeaderText="MODEL NUMBER" DataField="MODEL_NO" ControlStyle-CssClass="MODEL_NUMBER" >
<ControlStyle BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField HeaderText="SERIAL NUMBER" DataField="SERIAL_NO" ControlStyle-CssClass="SERIAL_NUMBER">
<ControlStyle BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField HeaderText="GROUP" DataField="GROUP" ControlStyle-CssClass="GROUP" >
<ControlStyle BorderWidth="1px" />
</asp:BoundField>
<asp:TemplateField HeaderText="LOCATION" ControlStyle-CssClass="LOCATION">
<ItemTemplate>
<asp:Label ID="Location" runat="server" Text='<%#Eval("BLDG")+ "-" + Eval("ROOM")%>' ></asp:Label>
</ItemTemplate>
<ControlStyle CssClass="LOCATION"></ControlStyle>
</asp:TemplateField>
<asp:BoundField HeaderText="DATE INSTALLED" DataField="INSTALLED" ControlStyle-CssClass="INSTALLED">
<ControlStyle BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField HeaderText="ACCOUNT" DataField="ACCOUNT" ControlStyle-CssClass="ACCOUNT">
<ControlStyle BorderWidth="1px" />
</asp:BoundField>
<asp:TemplateField HeaderText="OWNER" ControlStyle-CssClass="OWNER">
<ItemTemplate>
<asp:Label ID="Owner" runat="server" Text='<%#Eval("LAST")+ "," + Eval("FIRST")%>' ></asp:Label>
</ItemTemplate>
<ControlStyle CssClass="OWNER"></ControlStyle>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
</asp:Content>
Any help would be appreciated, thank you -- Novice Programmer
Whenever you bind a data to a data control in Page_Load event, please consider using Page.IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Equipment ORDER by BLDG", conn);
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
DA.Fill(ds);
View_Results.DataSource = ds;
View_Results.DataBind();
conn.Close();
}
}
This is because, when you click a button, your page will be still refreshed, which means the Page_Load event will be fired again, and you will bind the same data to gridview again, overwriting the Searched result set. You can check whether the page is loaded by a button click (Page.IsPostBack) or the page is loaded the first time (!Page.IsPostBack), and do your data binding accordingly.
I got this simple gridview
<asp:GridView ID="GridViewFoundations" runat="server" AutoGenerateColumns="False"
Width="100%" AllowPaging="True" AllowSorting="True" PageSize="15"
CellPadding="4" ForeColor="#333333" GridLines="None"
onpageindexchanging="GridViewFoundations_PageIndexChanging">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate><asp:Label ID="lb_id" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "nodeId") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Foundation Name">
<ItemTemplate><asp:Label ID="lb_foundationName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "text") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastUpdate">
<ItemTemplate><asp:Label ID="lb_lastUpdate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "updateDate") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expire Date">
<ItemTemplate><asp:Label ID="lb_expireDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "expireDate") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
Then I bind if on the page load event , like this
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void BindData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And i have the following filter (for example by text)
protected void btn_filtro_Click(object sender, EventArgs e)
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
My problem is I can't change the index of the page and keep my filters on..
I have already tried
GridViewFoundations.PageIndex = e.NewPageIndex
followed by
gridviewFoundations.Databind() or BindData()
but in the 1st case the gridview desapears and in the second it clears all the filters (obviously) .
So Can anyone help me changing the page of the grid with filters?
In first case(GridViewFoundations.PageIndex = e.NewPageIndex followed by gridviewFoundations.Databind() ) data disappears as you are not providing any datasource to rebing your grid after postback.
In second case(BindData()) you are binding grid without any filters, hence your filter is lost.
what you can do is create a new function
protected void BindFilteredData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
else
BindFilteredData();
}
This will call BindData when your page loads first time and rest of the times it will call filtered data function.
This is my aspx page
<asp:GridView ID="GridViews1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None"
>
<Columns>
<asp:TemplateField HeaderText = "S.No">
<ItemTemplate>
<asp:Label ID="Sno" runat="server" Text= '<%#Eval("id")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Name">
<ItemTemplate >
<a href= "<%# Eval("Photo") %>" > <%# Eval("name") %> </a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Photo">
<ItemTemplate>
<img src='<%# Eval("Photo") %>' alt='<%# Eval("Name") %>' height= "50px" width = "50px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
and this is my .cs file
public partial class people_db_mysql : System.Web.UI.Page
{
String MyConString = "SERVER=localhost;" +
"DATABASE=shortandsweet;" +
"UID=root;" +
"PASSWORD=;";
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(MyConString);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM people_details;", conn);
conn.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridViews1.DataSource = dataTable;
GridViews1.DataBind();
}}
now the output i get is
[ S.NO, Name , Photo , sno, name and photo ]
the first three fields are from the aspx page which i want it to be displayed and i dont want the other 3 fields to be displayed any ideas how i might achieve that ?
and moreover ive tried this
GridViews1.Columns[3or4or5].Visible = false; //and it says array out of bounds
however i can hide the 0,1,2 fields with the same command, is there a way to hide the rows generated through the .cs files ?
if i try to limit the rows through the select query it doesnt display anything, i just get a blank screen.
The Gridview control has a property 'AutoGenerateColumns' which has to be set to 'false', otherwise it will autogenerate the columns, even if you have manually added them.
<asp:GridView ID="GridViews1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="false"
>
i have a problem with my gridview contains a textbox to set a date.
<asp:gridview ID="Gridview1" runat="server" AllowPaging="True"
AutoGenerateColumns="False"
DataSourceID="AccessDataSource1" CellPadding="8" ForeColor="#333333"
GridLines="None" CellSpacing="5" Height="361px" Width="748px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="nome" HeaderText="Nome Utente"
SortExpression="nome" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="titolo" HeaderText="Titolo Libro"
SortExpression="titolo" >
<ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:BoundField DataField="Expr1" HeaderText="Data Restituzione Prevista"
ReadOnly="True" SortExpression="Expr1" >
<ItemStyle HorizontalAlign="Center" /></asp:BoundField>
<asp:TemplateField
HeaderText="Data Restituzione" SortExpression="Expr2">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Expr2") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Expr2") %>'
AutoPostBack="True" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:gridview>
And it is my asp.cs file:
namespace Utenti_Biblio
{
public partial class prestiti : System.Web.UI.Page
{
bool changed = false;
protected void Page_Load(object sender, EventArgs e)
{
selectRow();
}
public void selectRow()
{
foreach (GridViewRow row in this.Gridview1.Rows)
{
TextBox textBox = (TextBox)row.Cells[3].FindControl("TextBox1");
string a = textBox.Text;
if (a != "")
{
row.Cells[3].FindControl("TextBox1").Visible = false;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
changed = true;
}
// salva
protected void Button1_Click(object sender, EventArgs e)
{
if (changed)
{
foreach (GridViewRow row in this.Gridview1.Rows)
{
TextBox textBox = (TextBox)row.Cells[3].FindControl("TextBox1");
string qry = "UPDATE b_prestiti SET data_restituzione ='" + textBox.Text + "' WHERE id_utente = '" + row.Cells[1].ToString() + "'";
OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
OleDbCommand cmd = conn.CreateCommand();
OleDbDataReader reader = null;
conn.Open();
cmd.CommandText = qry;
reader = cmd.ExecuteReader();
ClientScript.RegisterStartupScript(this.GetType(), "conferma", "alert('Data Restituzione inserita!');window.location='Default.aspx';", true);
reader.Close();
conn.Close();
}
}
}
}
}
How i do to update the database when i set the date into my textbox?
The query string is not correct. Thanks!
Instead of the ExecuteReader() use ExecuteNonQuery(), that might do the trick.
GxG is right. ExecuteReader() is use to fetch the single record(Column) while to DML(Data Manipulation Language, like INSERT,DELETE,UPDATE) we use ExecuteNonQuery().