I tried looking this one up online, but I guess I'm not sure how I should phrase the question without a full explanation.
I've got a webform with a search bar. When you enter in a search term, it queries a database and pulls information and populates a gridview. I'm using the following code:
string find = "SELECT tblShipments.ShipmentID as [Shipment ID], tblShipmentsAssets.DateShip as [Date Shipped], FROM tblShipments INNER JOIN(tblAssets INNER JOIN tblShipmentsAssets ON tblAssets.AssetID = tblShipmentsAssets.AssetIDFK) ON tblShipments.ShipmentID = tblShipmentsAssets.ShipmentIDFK where(AssetIDFK like '%' + #assetidfk + '%' )";
OleDbCommand comm = new OleDbCommand(find, con);
comm.Parameters.Add("#assetidfk", OleDbType.Char).Value = TxtSearch.Text;
con.Open();
comm.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "AssetIDFK");
SearchGridView.DataSource = ds;
SearchGridView.DataBind();
In the past, I've simply populated a gridview solely with aspx code using <asp:SqlDataSource> and there I was able to get at the columns that held dates withing the <columns> tag and add in a DataFormatString="{0:d}" to get the format I wanted:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" HorizontalAlign="Center">
<Columns>
<asp:BoundField DataField="NextCal" HeaderText="Calibration Due" DataFormatString="{0:d}" >
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Database %>" ProviderName="<%$ ConnectionStrings:Database.ProviderName %>" SelectCommand="SELECT , [NextCal] FROM [tblAssets]"></asp:SqlDataSource>
With my C# method of populating the gridview, I have no <Columns> section to change the data format. I would then assume I need to do this in the code behind, however I'm not sure how to do that.
Figured out what I was doing wrong:
By having <AutoGenerateColumns ="true">, my columns were (big surprise) being automatically generated and then me adding in columns under the tag in .aspx was generating duplicate columns.
I changed it to <AutoGenerateColumns ="false">, manually entered my columns in under the tag and used the DataFormatString="{0:MM/dd/yyyy hh:mm tt}"to change the date format.
Sorry for the dumb question. Hopefully this will help someone avoid the same mistake..
Related
The code here creates a dropdown menu of abbreviations for different location. What I'm trying to do is to get all the abbreviation in alphabetical order. How do I go about doing that?
<asp:DropDownList ID="ddl_loc" runat="server" DataSourceID="CriticalLog"
DataTextField="abbrev" DataValueField="recordKey" Height="16px"
style="margin-bottom: 8px"
ToolTip="Select your Location for updating." AutoPostBack="True"
onselectedindexchanged="ddl_loc_SelectedIndexChanged"
AppendDataBoundItems="True" CssClass="auto-style9" Width="184px">
<asp:ListItem Value="-1">"-- Choose a Location --"
</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="CriticalLog" runat="server"
ConnectionString="<%$ ConnectionStrings:CriticalLogConnectionString %>"
SelectCommand="SELECT DISTINCT [name], [recordKey],[abbrev], [phone2], [phone1] , [type] FROM [location] where [name] NOT LIKE '(%' ORDER BY [type],[abbrev]">
</asp:SqlDataSource>
<div class="auto-style6">
<asp:Label ID="lbl_Loc" runat="server" Font-Bold="True" Font-Size="Large"
Font-Underline="True" ToolTip="Location"></asp:Label>
</div>
Well, you useally need (have) some data source for the drop down.
So, say this drop down:
<h3>Select Hotel</h3>
<asp:DropDownList ID="cboHotel2" runat="server"
DataValueField="ID"
DataTextField="HotelName"
Width="288px">
</asp:DropDownList>
Now, to fill above, we go:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCombo2();
}
void LoadCombo2()
{
string strSQL = "SELECT ID, HotelName FROM tblHotels ORDER BY HotelName";
DataTable rst = MyRst(strSQL);
cboHotel2.DataSource = rst;
cboHotel2.DataBind();
cboHotel2.Items.Insert(0, new ListItem("Please Select", "0"));
}
And now we see this:
So, really, the "common" way to approach this problem, is we order/sort and setup the data BEFORE we sent it to the drop down list.
And I did use that helper routine MyRst, since that just saves a lot of re-typing of code. that helper routine (I usually put in a global set of routines - used it for years). Is this:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, be it some list, some table, or whatever data you have to drive the combo box? Sort the data before you SEND the data to the drop down.
Lists, even tables (default view) all have the ability to sort - even if the original source data was not sorted.
Just change your SelectCommand's order by:
SelectCommand="SELECT DISTINCT [name], [recordKey],[abbrev], [phone2], [phone1] , [type] FROM [location] where [name] NOT LIKE '(%' ORDER BY [abbrev]"
I'm trying to create a web page with the aps.net framework and I connect to the SQL server successfully and I want to display the data from the database in the Grid View and there are a search box and dropdown list but there is an error when I try to search
this is the error message:
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
and my code viewpage1.aspx
the GridView
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Format="dd/MM/yyyy" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="InvoiceID" DataSourceID="SqlDataSource3">
<AlternatingRowStyle BackColor="#CCCCCC" />
-and this the sqldatasource
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:connStr %>" SelectCommand="Select * from [Portal].[fn_GetInvoices] (#SearchText) where CompanyCode=#CompanyCode and InvoiceDate between #fromDate and #toDate">
<SelectParameters>
viewpage1.aspx.cs
sqlcomm.CommandText = sqlquery;
sqlcomm.Connection = sqlconn;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcomm);
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
This is a common error message.
I OFTEN use the wizards to build a gridview I use this:
From above, I choose create new data source.
I let the wizard run.
BUT THEN we wind up with some MESSAY sqldatasource in the web page. I do NOT like them, and they NEAR ALWAYS just cause you pain.
So, what I will then do this:
Remove the sqldata source from the web markup - you don't' need that mess anyway.
eg this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CSharpWebApp.Properties.Settings.TEST4 %>"
SelectCommand="SELECT [ID], [Fighter], [Engine], [Thrust], [Description], [ImagePath]
FROM [Fighters]"></asp:SqlDataSource>
DELETE the above!!!!
Now WHEN you WILL use code to load up the Gridview? Then you ALSO must turn off (remove) the fact that you NOT GOING to use the sql data source anymore.
So in your GV, remove this:
So, all that error message is telling you is you are trying to set the data source in "code" but you ALREADY have a sql datasource setup in the markup.
So, get in the habit of blowing out and removing the sqldata source on the page, and ALSO remove the GV data source setting in the markup.
So, now say I will have this GV, and NOT have ANY data source in the markup in the web page. (and I recommend you do this). So, I still VERY often use the wizards. Even for a dropdown list, a gridview, repeaters, and even listview (my favorite).
So, run wizards - build the markup
Then blow out (remove) the SqlDataSource, and the
DataSourceID="SqlDataSource1" from the control (in this case gv).
So, as noted, you cannot have BOTH a DataSourceID="SqlDataSource1" and THEN try to use code. It is one or the other - and that's what the error message is telling you.
So, now we have this markup:
(and the wizards generated most of this for me!!!)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
OnClientClick ="popimage(this);return false"
ImageUrl = '<%# Eval("ImagePath") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Just nice clean markup - no Sqldatasource junk.
Now we are free to write normal code like a normal human, and we can fill the grid like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters", conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And our results are now this:
Ok, so now lets add a search box above the GV to search the GV.
Say you can type in the first few chars of the Fighter jet name, and we want to filter by that:
So, drop in a text box above the GV, + search button.
We now have say this:
<asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="search"
style="margin-left:15px" CssClass="btn"
/>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
So, now the page with searching looks like this:
Say we search for Lockheed - but even just typing in Lock would be fine.
thus:
And now our code can say be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid("");
}
void LoadGrid(string MySearch)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
if (MySearch != "")
{
cmdSQL.CommandText += #" WHERE Fighter LIKE #Fighter + '%'";
cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
}
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
protected void cmdSearch_Click(object sender, EventArgs e)
{
LoadGrid(txtSearch.Text);
}
}
So, I am STRONG suggesting that you DUMP the sqldata source on the web page markup. Such Sqldata soruces on the page can be great for one time load or data display. But the VERY instant you want control, filters, and need to use code?
Quite much the SAME instant it is time to drop and toss out and remove the data source from the web markup. You be glad you did, and as you can see, you now have 100% EASY AND SIMPLE control of the data you shove into the GV, and that includes endless possible use of simple code and buttons to add filters etc. to that data.
I have a SQL database that store values input via a text box. This then displays the values of that database on my output screen via a gridbox. Is there a way I can give the user the an option of which column he wants to delete? Like a delete button near the value in the gridbox.
If not how do I delete a variable column number in SQL. Like, If the user wants to delete line say 10. How do I incorporate that in my SQL delete command.
Should it incorporate the 'top' command? If so how?
protected void Button3_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = ("Data Source=abc; Initial Catalog=VisualStudioTest; User ID=USER; Password=PASS");
sc.Open();
SqlCommand com = new SqlCommand();
com.Connection = sc;
com.CommandText = ("delete from notes");//initially I've kept this to delete everything.
com.ExecuteNonQuery();
sc.Close();
Response.Redirect(Request.RawUrl);
}
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<Columns>
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:VisualStudioTestConnectionString3 %>"
SelectCommand="SELECT [Notes] FROM [Notes]"
OnSelecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>
i assume your goal is to delete a single row.
the simplest way that comes to my mind is to add a identity field as a key for the table, add the new column to the DataKeyNames list of the GridView and then add a parameter to the DeleteQuery in the SqlDataSource:
delete from notes where identityCol = #identityCol;
the last step is to add the delete control to the Gridview.
(this is another question, since my original post, I asked too many questions in one)
Let me state this first. I am pretty much completely new to ASP coding. I am working on a little side project that requires me to use ASP instead of PHP that I sort of did before. I have been looking at solutions for past 2 days, and have tried many things, but can't seem to get it to work with my code. I have been part of this site for some time, so I do know how it works. I would not be asking here if I wasn't already trying to do this on my own for some time. I have learned a huge amount of information about SQL on here, so I hope to do the same with ASP.
Question:
Number of Returned Rows display
When the page initially loads, it has only a TextBox1 and a Button. If I don't enter anything in the box and hit the button, it will load my GridView with all the Data rows from the SQL Select. When I do hit the button, I would like to display the amount of rows that has been returned next to the button.
GridView1 :
<asp:TextBox ID="TextBox1" runat="server" Width="265px" Height="22px" CssClass="myBox"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search Fields" CssClass="myButton" />
<asp:GridView ID="GridView1" OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_Sorting" runat="server" AutoGenerateColumns="true" CellPadding="4" EnableModelValidation="True" EnableTheming="True" ForeColor="#333333" GridLines="None" Width="100%" style="margin-top: 0px; text-align: center;" AllowPaging="True" AllowSorting="True" >
<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" />
</asp:GridView>
Code Behind (DB name and Password taken out):
SqlConnection vid = new SqlConnection("Data Source=ENF;Initial Catalog=***Database Name***;Persist Security Info=True;User ID=sa;Password=***Password***");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String str = "SELECT ab.NAME as [Customer] ,ISNULL(ab.TELEPHONE1,'') as [Phone #] ,ISNULL(pb.NAME,'') as [Product] ,ISNULL(aeb.NEW_PRODUCTVERSION,'') as [Version] ,CASE WHEN ab.STATUSCODE = 1 THEN 'Active' ELSE 'Inactive' END as [Status] ,ISNULL('Sal : ' + c.SALUTATION + ' / ','') + ISNULL('Title : ' + c.JOBTITLE + ' / ','') + ISNULL(a.PRIMARYCONTACTIDNAME,'') as [Primary Contact] ,ISNULL(c.TELEPHONE1,'') as [Contact Phone] FROM ACCOUNTBASE ab LEFT JOIN ACCOUNTEXTENSIONBASE aeb on ab.ACCOUNTID = aeb.ACCOUNTID LEFT JOIN PRODUCTBASE pb on aeb.NEW_PRIMARYPRODUCTID = pb.PRODUCTID LEFT JOIN ACCOUNT a on ab.ACCOUNTID = a.ACCOUNTID LEFT JOIN CONTACT c on a.PRIMARYCONTACTID = c.CONTACTID WHERE ((ab.NAME LIKE '%' + #search + '%') OR (aeb.NEW_PRODUCTVERSION LIKE '%' + #search + '%') OR (pb.NAME LIKE '%' + #search + '%') OR (a.PRIMARYCONTACTIDNAME LIKE '%' + #search + '%')) ORDER BY ab.NAME";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView1.DataSource = ds;
GridView1.DataBind();
vid.Close();
}
Amount of rows that has been returned will store in instance of dataset. so by taking the count you will get the returned row information.The DataSet contains rows, columns,primary keys, constraints, and relations with other DataTable objects. We can get the number of rows from in a Table inside a Dataset by using its Rows.Count property.
ds.Tables[0].Rows.Count
I am on Linux now and I am coding in RoR.... I cannot test now...
But if you need to know how many items has your GridView, just use:
int qty = GridView1.Rows.Count;
Is it what you need?
Some samples... always find in MSDN abour Microsoft Developer info, There are a lot of stuff there!
http://msdn.microsoft.com/library/system.web.ui.webcontrols.gridviewrowcollection.count%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rows%28v=vs.110%29.aspx
To get the total rows
int TotalRecord = dt.Rows.Count();
You can probably just set everything in your OnClick event but if it doesn't work you may have to set your row count when the gridview is being created and then I would create a label and set the label = TotalRecord.text. make the label.visible=False and in your buttons onclick event set the label.visible = true.
If you don't want to show the count until the user clicks the button, this means that you are getting the count on the post back, and not on the original display of the page. But you populate the gridview on the original display. So at the time of the postback, you no longer have the dataset available, so you can't just say textbox1.text=ds.tables(0).rows.count. You would have to either (a) rerun the query, which seems like a waste of resources, or (b) stash the count somewhere on the initial load.
I'd suggest (b). You could populate the text box on the initial load and hide it (textbox1.visible=false). Or you could create a hidden field to keep the count, or put it in the view state, and then retrieve it from there when you need it.
Two by the ways:
One: I'd use meaningful names for controls rather than "textbox1" and "gridview1". It's a lot easier to read a program that says
if update_order.checked then ...
rather than
if checkbox1.checked then ...
Two: You have some unnecessary steps in your database call. You don't need the xp.ExecuteNonQuery. The fill() will execute the query. You're running it twice: the first time you throw away the results, and then the second time you process them. Also, you don't normally need to specify the data type on your parameters. You can just write
xp.parameters.AddWithValue("#search",textbox1.text)
Again, I know this has been answered many a time, but I'm getting confused with all the examples. So I'll ask it in the way I need answered.
I have a sql table, supplylinks. this has rowid (identity pk), title (varchar), link (varchar) and description (varchar).
The link field is an actual hyperlink, a url.
So for arguments sake, lets say the first row is:
1 | Google | http://www.google.com | Google Search engine
Easy enough.
Now I'm loading this into a gridview.
Nothing fancy, all done in c# code.
SqlConnection conn = new SqlConnection(#"Server=DEV6\MSSQLHOSTING;Database=Intranet;Trusted_Connection=True;");
ds = new DataSet("ds");
if (type.Equals("SAIX"))
{
SqlDataAdapter da = new SqlDataAdapter("select [Title],[Link],[Description] from SupplierLinks where SuppRowID = " + index, conn);
da.Fill(ds);
}
if (type.Equals("Domian Related Links"))
{
SqlDataAdapter da = new SqlDataAdapter("select [Title],[Link],[Description] from DomainLinks where SuppRowID = " + index, conn);
da.Fill(ds);
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
grdLinks.DataSource = ds;
grdLinks.DataBind();
}
}
else
{
lblDisp.Text = "";
lblError.Text = "There are no links for that type";
}
Nothing wrong there. I get my info. But I want to now make the link that is returned by the sql table and put into the gridview as a proper link so that when someone clicks on the link, they are redirected to Google, in this instance.
Please help. All other coding around here is confusing me. Lots are saying I must add a hyperlink column to the gridview. But where?
I was getting so far, then got lost as to what to bind.
<asp:GridView ID="grdLinks" runat="server">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="col2"
</Columns>
</asp:GridView>
Like I said, I'm lost and confused.
Thank you in advance.
<Columns>
<asp:HyperLinkField DataTextField="LeadID" DataNavigateUrlFields="LeadID" DataNavigateUrlFormatString="LeadInformation.aspx?LeadID={0}" Text="Lead ID" />
<asp:BoundField DataField="DateTime" HeaderText="Date Updated" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Bind("LeadID") + Request.QueryString("type") %>' Text=""></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Hope this will help you
all I needed was
<a href='<%# Eval("Link") %>'>
<asp:Label ID="LinkLabel" runat="server" Text='<%# Eval("Link") %>' /></a>
in my listview.