Here is the code i make, and plese help me to create function to show datatable when i click the button.
protected void Button1_Click(object sender, EventArgs e)
{
str = "Select count(name) as total, sum(case when status = 'DONE' then 1 else 0 end) as total_done, sum(case when status = 'PROGRESS' then 1 else 0 end) as total_progress from person where name = 'RAKA'";
cmd = new MySqlCommand(str, con);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tot1.Text = reader["total"].ToString();
done1.Text = reader["total_done"].ToString();
prgs1.Text = reader["total_progress"].ToString();
tb1. = reader["total"].ToString();
}
}
Ok, in most cases to display some data, you don't need a loop.
However, you do want to use say a gridview (which is table anyway - just with nice fancy and easy to use asp.net stuff wrapped around it).
So, say you have this markup:
<div style="padding:35px;width:40%">
<asp:GridView ID="GridView1" runat="server" CssClass="table">
</asp:GridView>
</div>
So, now in the code behind, to load this grid (table) up, you can use this code:
protected void Button1_Click(object sender, EventArgs e)
{
string str =
"Select count(name) as total, sum(case when status = 'DONE' then 1 else 0 end) as total_done, "
+ "sum(case when status = 'PROGRESS' then 1 else 0 end) as total_progress from person where name = 'RAKA'";
DataTable rstData = new DataTable();
using (MySqlConnection con = new MySqlConnection(Properties.Settings.Default.TEST4))
{
using (MySqlCommand cmd = new MySqlCommand(str, con))
{
con.Open();
rstData.Load(cmd.ExecuteReader());
}
}
// now send data table to grid view
GridView1.DataSource = rstData;
GridView1.DataBind();
}
So, you want using System.Data - that is the basic table and rows and operations. That part (ado.net) is the basic objects you need. You then adopt your "provider".
for exmaple, I don't have MySQL installed, but I using sql server. So ONLY the provider part need be change.
So with above markup, I can fill out the gridview 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 * FROM Fighers";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And I now see/get this on the page:
but, often I will use the wizards to create the grid, and then REMOVE the data source on teh page, and use my above code. (I use the wizrard to setup the grid view, since I am lazy.
But, lets tweak up the gird. I don't want "ID", and the path name to the image, lets drop in a iamge control.
So, my markup now becomes this:
<div style="padding:35px;width:50%">
<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:Image ID="Image1" runat="server" width="150px"
ImageUrl = '<%# Eval("ImagePath") %>' /> />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="View" CssClass="btn" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code can be as before.
So, I added a image control to the grid, and a button.
So now we see/get this:
Again, note how we did NOT use a loop. But we fill out a table, and then send that table to the grid view.
And the above idea quite much applies to any kind of repeating data.
So, you can use repeater, a Gridview, listview, datalist view etc. You can feed such controls "repeating" data, and thus no need for some loop to try and fill out controls. (and if you need repeating data, then how do you add more controls to the page - that's too hard. So, use the data aware controls, and they will render that type of data for you, especially for repeating types of data.
Related
I have a following markup on my web page:
<asp:GridView ID="GridView" runat="server"
AutoGenerateDeleteButton="True"
<Columns>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<% #Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
I am trying to get the value of the text field to get the correct ID of the row that I want to be deleted, however I do not know how to exactly do it, I have tried following code:
Protected Sub GridView_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView.RowDeleting
Dim row As GridViewRow = GridView.Rows(e.RowIndex)
Dim ID As Integer = TryCast(row.FindControl("lblID"), TextBox).Text
...
However after clicking on the delete button on the generated web page I just get error:
"Object reference not set to an instance of an object."
Visual Studio points the error to the "TryCast".
I can not find any similar examples and do not understand what is happening, if somebody has a better idea of getting that ID value that would also work?
Your lblID control certainly is a label defined by this control markup:
<asp:Label ID="lblID" runat="server" Text='<% #Eval("ID")%>'></asp:Label>
On this line you tried to cast the label control as TextBox instead of Label, so it returns Nothing and throwing NullReferenceException when accessing Text property:
Dim ID As Integer = TryCast(row.FindControl("lblID"), TextBox).Text
What do you need is cast to Label and get Text property there:
Dim ID As Integer = Convert.ToInt32(TryCast(row.FindControl("lblID"), Label).Text)
Note that Convert.ToInt32 added because Text property of a label control contains string value, hence casting to Integer is necessary. If you're not sure it will return Nothing, use Integer.TryParse instead.
I'm Having a problem regarding to the autocomplete textbox. First I already made the autocomplete textbox work with mysql database as custom source but the default textfilter of autocomplete is "start with" not "contains". I want to change the textfilter to "contains", so that when I search any part of the string, the whole name which contains the searched word will appear in the autocomplete suggestions.
Can anyone help me fix my code?
This is the code i've done so far:
txtSearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim DataCollection As New AutoCompleteStringCollection()
Dim query As String
sqlcon = New MySqlConnection
sqlcon.ConnectionString =
"server=localhost;userid=root;password=root;database=svfmemberlistdb"
Try
sqlcon.Open()
query = " SELECT Name FROM svfmemberlistdb.svfmemberlist "
sqlcmd = New MySqlCommand(query, sqlcon)
sqladr.SelectCommand = sqlcmd
sqladr.Fill(ds)
sqladr.Dispose()
sqlcon.Close()
For Each row As DataRow In ds.Tables(0).Rows
If row.ToString.Contains(txtSearch.Text) Then
DataCollection.Add(row(0).ToString())
End If
Next
Catch ex As Exception
End Try
txtSearch.AutoCompleteCustomSource = DataCollection
I quote here Mitja Bonca's answer on MSDN.
In this case, autocompletemode will just not do. Its code is not meant
for something like it.
You will have to do your own code, to do the filtering on each letter
press.
So I would suggest not to use autocompletemode, and get all the data
(names) into dataTable. When user presses some button ("1" for
example), you start with your filtering, by creating new Datatable
(leave the main one untached - so you can return back to all data when
clearing comboBox by backspace), with Copy() method - to create a full
copy of original one, and use Select method to do the filteing.
This should look something like by using % simbol on both sides of a
string - to filter inbetween - this is what you want!
DataTable AllNames = new DataTable();
//fill it up and leave it untouched!
//to filter comboBox with names that contains pressed characters do in
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string name = string.Format("{0}{1}", comboBox1.Text, e.KeyChar.ToString()); //join previous text and new pressed char
DataRow[] rows = table.Select(string.Format("FieldName LIKE '%{0}%'", name));
DataTable filteredTable = AllNames.Clone();
foreach(DataRow r in rows)
filteredTable.ImportRow(r);
comboBox1.DataSource = null;
comboBox1.DataSource = filteredTable.DefaultView;
comboBox1.DisplayMember = "FieldName";
}
Reference
EDIT: This is of course a c# answer not VB.NET but it might be helpful to get the concept.
I select checkboxes in the datatable and press button and when i return to the page, it got deselected. i want the selection to be saved after navigation. it is like i select few of the candidates as shortlisted and go next, and if i want to make some changes to amend the list and go back then i want the already checked candidates to be checked but actually when im returning to the page, it refreshes
button for selection::::
<f:param name="currentPage" value="#{nav.ShortListed}" />
<f:setPropertyActionListener target="#{pageManager.prevNavigation}" value="#{nav.New}" />
code for returning to the same page:
and the respective bean
public void revertShortListPanel() throws SQLException
{
Session hibernateSession = HibernateUtil.currentSession();
Connection con = hibernateSession.connection();
//.............removing all offrs from offr_panel table...........revert short listing
this.customSelectedOffrs = new ArrayList<CriteriaSearchDao>();
this.selectedRows = new CriteriaSearchDao[customSelectedOffrs.size()];
String sql1 ="delete from OFFR_PANEL where PANEL_ID = ? ";
String sql2 = "update TBL_PANEL set PANEL_STATUS ='New' where PANEL_ID=? ";
PreparedStatement pnlStatus1 = con.prepareStatement(sql1);
PreparedStatement pnlStatus2 = con.prepareStatement(sql2);
I have this table.
https://www.dropbox.com/s/7xf6ibn5mr9f9yf/test4.PNG?dl=0
Basically, I want to display "AttendDet_Type" which is P, A and MC as the x-axis using multiple series (which will look like this - https://www.dropbox.com/s/v15pp818tmgf8co/test5.PNG?dl=0) and COUNT(AttendDet_Type) as the y-axis.
I managed to display AttendDet_Type for P using asp chart but I totally have no idea how to code multiple series to display A and MC. Can anyone help me out?
My ASP Code
<asp:Chart ID="Chart1" runat="server" SqlDataSourceID="SqlDataSource1" Width="800" Height="500">
<Titles>
<asp:Title Text = "Attendance Report"></asp:Title>
</Titles>
<Series>
<asp:Series Name="Series1">
</asp:Series>
<asp:Series ChartArea="ChartArea1" Name="Series2">
</asp:Series>
<asp:Series ChartArea="ChartArea1" Name="Series3">
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1" >
</asp:ChartArea>
</ChartAreas>
My VB Code
Using con As New MySqlConnection(ConfigurationManager.ConnectionStrings("ConString").ConnectionString)
Dim CmdString As String = "SELECT Attendance.AttendDet_Type, COUNT(Attendance.AttendDet_Type) AS TotalAttendance FROM Student, Attendance WHERE Student.Stud_ID = Attendance.Stud_ID AND Student.Stud_Class = '1A1' AND Attendance.Attend_Date = '2014-11-12' AND AttendDet_Type = 'P'"
Dim sda As New MySqlDataAdapter(CmdString, con)
Dim ds As New DataSet()
sda.Fill(ds)
Chart1.DataSource = ds
Chart1.Series("Series1").XValueMember = "AttendDet_Type"
Chart1.Series("Series1").YValueMembers = "TotalAttendance"
Chart1.DataBind()
End Using
Looking forward to receiving yall replies. Thanks!!
In my Windows Phone Mango app, I have a bunch of checkboxes, each corresponding to a day of the week. I want to filter the data I query by which checkboxes are checked. Here's what I've come up with, but I feel like there's a better solution:
Declare the checkboxes in XAML:
<CheckBox Content="Mon" x:Name="MonCheckbox" Checked="DayCheckbox_Tap" Unchecked="DayCheckbox_Tap"/>
<CheckBox Content="Tue" x:Name="TueCheckbox" Grid.Column="1" Checked="DayCheckbox_Tap" Unchecked="DayCheckbox_Tap" />
<CheckBox Content="Wed" x:Name="WedCheckbox" Grid.Column="2" Checked="DayCheckbox_Tap" Unchecked="DayCheckbox_Tap" />
<CheckBox Content="Thur" x:Name="ThurCheckbox" Grid.Row="1" Checked="DayCheckbox_Tap" Unchecked="DayCheckbox_Tap" />
<CheckBox Content="Fri" x:Name="FriCheckbox" Grid.Row="1" Grid.Column="1" Checked="DayCheckbox_Tap" Unchecked="DayCheckbox_Tap" />
<CheckBox Content="Sat" x:Name="SatCheckbox" Grid.Row="1" Grid.Column="2" Checked="DayCheckbox_Tap" Unchecked="DayCheckbox_Tap" />
<CheckBox Content="Sun" x:Name="SunCheckbox" Grid.Row="2" Grid.Column="0" Checked="DayCheckbox_Tap" Unchecked="DayCheckbox_Tap" />
Associate a day with each checkbox:
public MainPage()
{
InitializeComponent();
LayoutRoot.DataContext = this;
// This is grossly imperative. Can it be done in XAML?
MonCheckbox.Tag = DayOfWeek.Monday;
TueCheckbox.Tag = DayOfWeek.Tuesday;
WedCheckbox.Tag = DayOfWeek.Wednesday;
ThurCheckbox.Tag = DayOfWeek.Thursday;
FriCheckbox.Tag = DayOfWeek.Friday;
SatCheckbox.Tag = DayOfWeek.Saturday;
SunCheckbox.Tag = DayOfWeek.Sunday;
// ...
}
Maintain a collection of the currently selected days:
ICollection<DayOfWeek> _selectedDays = new Collection<DayOfWeek>();
private void DayCheckbox_Tap(object sender, RoutedEventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
if (_selectedDays.Contains((DayOfWeek)checkbox.Tag))
{
_selectedDays.Remove((DayOfWeek)checkbox.Tag);
}
else
{
_selectedDays.Add((DayOfWeek)checkbox.Tag);
}
refreshCheckinData();
}
The problem comes when I go to refresh the data that's displayed to the user:
private void refreshCheckinData()
{
Checkins.Clear();
Checkins.AddAll(from checkin in checkinData.Items
where _selectedDays.Contains(checkin.DateTime.DayOfWeek)
select checkin);
}
public static class ExtensionMethods
{
public static void AddAll<T>(this ICollection<T> dest, IEnumerable<T> source)
{
if (dest == null)
{
throw new ArgumentNullException("dest");
}
foreach (T t in source)
{
dest.Add(t);
}
}
}
When the code tries to iterate over source in AddAll(), the following exception occurs:
Method 'Boolean Contains(System.DayOfWeek)' has no supported translation to SQL." System.Exception {System.NotSupportedException}
How can I get around this? Why does Contains require a SQL translation? Is there a better approach to this whole thing, using more declarative XAML and less imperative code-behind?
Update: I tried changing the query to:
where _selectedDays.Any(day => day == checkin.DateTime.DayOfWeek)
now I get the following error:
"Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator." System.Exception {System.NotSupportedException}
_selectedDays is defined in memory. why does it need to be translated to SQL?
Your original query is close. I think the Contains() method on ICollection is getting in the way of the SQL translator -- I would need to double check the code to be sure.
You can work around this by forcing selection of the Enumerable.Contains() extension method by changing your code to this:
private void refreshCheckinData()
{
Checkins.Clear();
Checkins.AddAll(from checkin in checkinData.Items
where _selectedDays.AsEnumerable().Contains(checkin.DateTime.DayOfWeek)
select checkin);
}
Enumerable.Contains(T) extension method will translate into an IN clause in the database.
The resulting query will be something like this:
SELECT [t0].[Key], [t0].[Day]
FROM [Stuff] AS [t0]
WHERE [t0].[Day] IN (#p0, #p1)
If i understand it correctly then you wanna add all selected days to your 'Chekings' so why don't you try this code, i think this will solve your problem for now and to answer the other questions i have to think about them a bit a do some research. :)
foreach(var day in _selectedDays)
{
Checkins.AddAll(from checkin in checkinData.Items
where checkin.DateTime.DayOfWeek == day
select checkin);
}
Would have to test this one i don't know if it works or not or if it is even valid.
from checkin in checkinData.Items
join sdays in _selectedDays on checkin.DateTime.DayOfWeek == sdays
select checkin