I just cant figure out how to get the output of a query and be able to manipulate it, meaning that i have a database and i have a table named CoursePages that contain all the coursePages in my university, so when a student or somebody wants to subscribe to a course page i want to view all the records in the table(coursePages) and make them clickable just in order to know which one he/she pressed and save it. So is there any way to generate such thing ?
Here is my code :
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=JASONTT-PC\\SQLSERVER;Initial Catalog=GNetwork;Integrated Security=True";
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.Connection.Open();
String query = "SELECT * FROM Course_Pages ";
comm.CommandText = query;
SqlDataReader reader = comm.ExecuteReader();
// i don't know what to do after i executed the reader ..
}
maybe like a gridView or sthg ... i just want for every record i will take the name (String ) and put it in a checkbox so that i can tell which ones the user clicked
while (reader.Read()){
//now you can get any values by column index like
int i = reader.GetInt32(0);
string s = reader.GetString(1);
double d = reader.GetInt32(2);
DateTime dt = reader.GetDateTime(3);
}
If you're asking how to translate these results into links on your web page, you should look at creating a gridview and Binding your reader to it.
Here's a sample:
using (SqlDataReader reader = comm.ExecuteReader()) {
gv1.DataSource = reader;
gv1.DataBind();
}
<asp:GridView runat="server" AutoGenerateColumns="false" ID="gv1">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:TemplateField>
<ItemTemplate>
<a href='foo.aspx?id=<%# Eval("id") %>'>Link</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Finally, note that if you have a field in your returned query that represents the url in toto, you can use a HyperLinkField
<asp:HyperLinkField DataNavigateUrlFields="linkHref" Text="BoundLink" />
DataNavigateUrlFields is the field from your results you're binding the url to.
Related
I have the below code-behind for an asp web page:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["TapeTrackingConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand("UpdateContainerBySID", con);
cmd.CommandType = CommandType.StoredProcedure;
// If you are passing any parameters to your Stored procedure
// cmd.Parameters.AddWithValue("#Parameter_name", Parameter_value);
// int Session = int.Parse(DropDownList1.Text);
// int Container = int.Parse(ContainerID.Text);
cmd.Parameters.AddWithValue("#ContainerID", ContainerID.Text);
cmd.Parameters.AddWithValue("#SessionID", DropDownList1.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The #ContainerID shows all numbers input into the asp textbox, and a Response.Write shows all the characters. However, when I check the database after the button click, it has only inserted the first number, not the whole number. ie: instead of 43263, it is inserting 4.
Here is the textbox and submit button code:
<asp:TextBox ID="ContainerID" MaxLength="10" runat="server" Columns="6" Rows="1" TextMode="Number"></asp:TextBox>
<asp:Button runat="server" Text="Submit" OnClick="Button1_Click" ></asp:Button>
I am a bit new to this, so I do appreciate the help!!!
Thanks!!
Jack
I have been working on this for a while but seems I can't figure this out. So I have a dropdown list called ddStudent where the textField value is from a sql table I made called 'Student from a column called 'firstName'. Now I used the 'studentID' as the value field.
Here is where I am having the issue. I want to execute my stored procedure that takes studentID as a paramter but I don't understand how to store the actual student ID into the parameter.
Here is what I have so far-
protected void btnRegister_Click(object sender, EventArgs e)
{
int selValClass = Convert.ToInt32(ddClassNames.SelectedValue);
int selValStudent = Convert.ToInt32(ddStudents.SelectedValue);
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("procRegStudent", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#studentID", selValStudent);
cmd.Parameters.AddWithValue("#classID", selValClass);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
and here is my code for databinding-
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT studentID, firstName, lastName, ssn, address, city, state, zip FROM Student ", con);
con.Open();
ddStudents.DataSource = cmd.ExecuteReader();
ddStudents.DataTextField = "firstName";
ddStudents.DataValueField = "studentID";
ddStudents.DataBind();
}
Now my question is, is there a way I can store the actual studentID from the dropdown list when I select it? For some reason when I do this, the page reloads and selects the first student ID for a student I didn't select. I'm not exactly sure what's going on.
Thanks.
EDIT-
I wanted to make sure I clarify-
I have 3 students in my student dropdown. When I select student 3 (with student ID 3), the first student in the dropdownlist is being passed as the parameter and I can't tell why.
This issue is logical for Dropdownlist control because your dropdownlist missed to have a defaultitem to render when it comes back from the server.The soultion is very simple you should add a default list item to be the default value when the page loads
Here I made a simple example to how can we solve this issue :
in the Page.aspx:
<asp:DropDownList ID="ddStudents" runat="server" DataTextField = "firstName" DataValueField = "studentID" AppendDataBoundItems="true">
<asp:ListItem Text="===Select Student===" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
in the Page.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
DataTable dt = new DataTable();
dt.Columns.Add("studentID", typeof(int));
dt.Columns.Add("firstName", typeof(string));
dt.Rows.Add(dt.NewRow());
dt.Rows[0]["studentID"] = 1;
dt.Rows[0]["firstName"] = "Markus";
dt.Rows.Add(dt.NewRow());
dt.Rows[1]["studentID"] = 2;
dt.Rows[1]["firstName"] = "Arthur";
ddStudents.DataSource = dt;
ddStudents.DataBind();
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (ddStudents.SelectedIndex > 0)
{
lblMessage.Text = String.Format("You selected {0} with Number : {1}", ddStudents.SelectedItem.Text,ddStudents.SelectedValue);
}
}
Hint: I marked the dropdownlist AppendDataBoundItems Property to true just to tell the dropdownlist to include the default listitem when the data binded..
I hope my code helps you solving your problem :)
Try with this
int selValStudent = int.Parse(this.ddStudents.SelectedValue);
and put your
BindDropDown();
into your postback
I've searched through a heap of similar questions and done a bit of googling but I cannot find the answer to my problem...
I would like to have a drop down list that is populated by categories in a database...upon selecting a category and hitting submit, a gridview is populated with all the items in that category.
Now, everything works, except whenever I select anything in the category drop down box, it resets straight away to the first selection. So I'm unable to submit any value other than the first to the gridview. I am using autopostback on this item. I have tried to use appenddatabounditems too but that just populated the list with more and more of the same entries...
I would love if anyone could tell me how I can just get the dropdownlist to hold its position after postback?
Selected Category:
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" ViewStateMode="Enabled">
</asp:DropDownList>
<asp:Button ID="buttonCategorySubmit" runat="server" OnClick="buttonCategorySubmit_Click" Text="Submit" />
<br />
</div>
<asp:GridView ID="CategoryGridView" runat="server">
</asp:GridView>
<br />
protected void Page_Load(object sender, EventArgs e)
{
PopulateCategorySelection();
}
public void PopulateCategorySelection()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);
SqlCommand cmd = new SqlCommand("AllCategories", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader ddlValues = cmd.ExecuteReader();
ddlCategory.DataSource = ddlValues;
ddlCategory.DataValueField = "CategoryID";
ddlCategory.DataTextField = "Title";
ddlCategory.DataBind();
conn.Close();
}
protected void buttonCategorySubmit_Click(object sender, EventArgs e)
{
PopulateCategoryTable();
}
public void PopulateCategoryTable()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["Connstring"]);
SqlCommand cmd = new SqlCommand("SelectCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Selected", ddlCategory.SelectedItem.Value);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
conn.Close();
CategoryGridView.DataSource = ds.Tables[0];
CategoryGridView.DataBind();
conn.Close();
}
I literally just worked it out everyone...For anyone that has the same issue, you need to check in the page_load method whether the page is loading because a new page is being generated, or information is just being posted-back for the user. If its just postback, we dont want to populate the category dropdown box again. So we use the IsPostBack object in the page_load method, like this:
if (!IsPostBack)
{
PopulateCategorySelection();
}
I have the following GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="SysInvoiceID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="SysInvoiceID" HeaderText="SysInvoiceID" ReadOnly="True" SortExpression="SysInvoiceID" />
<asp:BoundField DataField="BillMonth" HeaderText="BillMonth" SortExpression="BillMonth" />
<asp:BoundField DataField="InvoiceDate" HeaderText="InvoiceDate" ReadOnly="True" SortExpression="InvoiceDate" />
<asp:BoundField DataField="InvoiceNumber" HeaderText="InvoiceNumber" SortExpression="InvoiceNumber" />
<asp:BoundField DataField="Net" HeaderText="Net" SortExpression="Net" />
<asp:BoundField DataField="VAT" HeaderText="VAT" SortExpression="VAT" />
<asp:BoundField DataField="Gross" HeaderText="Gross" SortExpression="Gross" />
<asp:ButtonField CommandName="ViewInvoice" HeaderText=" " ShowHeader="True" Text="View" />
</Columns>
</asp:GridView>
Here is the code behind the page:
public partial class PagingTest01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "ViewInvoice")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Now you have access to the gridviewrow.
ViewButton_Click(row);
}
}
protected void ViewButton_Click(GridViewRow row)
{
byte[] FileImage = GetImageData(0,row);
if (FileImage != null)
{
base.Response.Clear();
base.Response.Buffer = true;
base.Response.ContentType = "Application/x-pdf";
base.Response.ContentEncoding = Encoding.Default;
string attachment = string.Format("attachment;filename=\"Invoice_{0}.pdf\"", "Customer1");
base.Response.AddHeader("content-disposition", attachment);
base.Response.BinaryWrite(FileImage);
base.Response.Flush();
base.Response.Close();
base.Response.End();
}
}
public byte[] GetImageData(int sysInvoiceID, GridViewRow row)
{
string strUserID = CommonCode.GetCurrentUserID().ToString();
string strCustomerID = CommonCode.GetCurrentCustomerID().ToString();
byte[] numArray;
string strConnectionString = "Data Source=TESTSERV;Initial Catalog=DB_Invoices;Persist Security Info=True";
SqlConnection connection = new SqlConnection(strConnectionString);
SqlCommand command = new SqlCommand("select FileImage from DB_Invoices.dbo.Bills WHERE (FileType = 'PDF' AND SysInvoiceID = #ID)", connection);
command.Parameters.AddWithValue("#ID", GridView1.Rows[row].Cells[0].Text);
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
try
{
connection.Open();
da.Fill(ds);
DataRow item = ds.Tables[0].Rows[0];
byte[] item1 = (byte[])item["FileImage"];
ds.Tables.Clear();
numArray = item1;
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
return numArray;
}
}
So basically I have a GridView with a lot of rows, each one with a 'View' Buttonfield next to it. When 'View' is clicked, I attempted to make use of GridView1_RowCommand which should hopefully grab the row clicked before passing it onto ViewButton_Click. This will then call GetImageData and pass the row number onto this line:
command.Parameters.AddWithValue("#ID", GridView1.Rows[row].Cells[0].Text);
Cell 0 is the SysInvoiceID column, so if the correct row is passed, #ID will be assigned a SysInvoiceID.
'Row' however doesn't seem to be a valid argument, though I can't think why not... Unless I have to explicitly convert it into a int? Any help would be really appreciated! Thanks.
I have just commented this as side-note but maybe it's your issue because you mention that "it doesn't seem to be a valid argument, though I can't think why not... Unless I have to explicitly convert it into a int".
If ID is an int you should use int.Parse(celltext), othwerwise the database gets the wrong type since AddWithValue needs to infer the type from the value.
So use:
command.Parameters.AddWithValue("#ID", int.Parse(GridView1.Rows[row].Cells[0].Text));
Apart from that, you haven't added the event handler GridView1_RowCommand.
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server" AutoGenerateColumns="False" DataKeyNames="SysInvoiceID" DataSourceID="SqlDataSource1">
....
and you are also not setting the CommandArgument to the index of the row. I would use a different approach anyway if you need the row-index. Use a templatefield and a control, for example a Button. Then use it's NamingContainer property to get the reference to the 'GridViewRow`, here is an example: Get Row Index on Asp.net Rowcommand event
use this:
int index = ((GridViewRow)((WebControl)sender)).RowIndex;
in place of
int index = Convert.ToInt32(e.CommandArgument);
What i have accordion being loaded with an issue, I want distinct header information and multiple rows in the content.
For example I have a DataTable with the following:
Fruit|Apples
Fruit|Mango
Vegetables|peas
I want it to result like this
Fruit
-Apples
-Mango
Vegetables
-peas
This is what I get right now.
Fruit
- Apples
Fruit
- Mango
Vegetables
- peas
The code i'm using to databind is below:
protected void Page_Load(object sender, EventArgs e)
{
CurrentUserID = HttpContext.Current.Session["userID"].ToString();
BindAccordion();
}
private void BindAccordion()
{
viewablePages = new List<string>();
string storedProcedureName = "GrabAccordionPages";
using (MySqlConnection cn = new MySqlConnection("Server="";Database=""; User=root;Password="";"))
{
List<string> roles = new List<string>();
cn.Open();
MySqlCommand cmd = new MySqlCommand(storedProcedureName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#usernameID", CurrentUserID);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dtTable = new DataTable();
da.Fill(dtTable);
NavigateAccordion.DataSource = dtTable.DefaultView;
NavigateAccordion.DataBind();
}
}
My accordion looks like
<ajaxToolKit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="Server" />
<ajaxToolKit:Accordion ID="NavigateAccordion" runat="server"
SelectedIndex="0"
HeaderCssClass="accordionHeader"
ContentCssClass="accordionContent"
FadeTransitions="true"
SuppressHeaderPostbacks = "true"
FramesPerSecond="80"
TransitionDuration="200"
AutoSize="None"
Width="200">
<HeaderTemplate>
<asp:Label runat="server" Id="lbHeaderId" Text='<%#Eval("service") %'>> </asp:Label>
</HeaderTemplate>
Is there a way to manipulate the <%#Eval("service") %'>> or do I need to create something besides a DataTable to accomplish what I need. Or can i bind two datasources to one accordion, but then how do i manage both sources in the content?
This is probably not the answer you were looking for but I would suggest skipping the Microsoft provided toolkits and start using something like jQuery/jQuery UI. I am sure someone in here will be able to help you out.