.aspx page something like this
<form id="Form1" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="0" width="600px" cellpadding="2" cellspacing="1" style="border: 1px solid maroon;">
<tr bgcolor="maroon">
<th> Subject_Id </th>
<th> Subject_Name </th>
<th> Fill_Marks </th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td width="100">
<asp:TextBox ID="Subject_Id" runat="Server" Text='<%#Eval("Subject_Id")%>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="Subject_Name" runat="Server" Text='<%#Eval("Subject_Name")%>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="Marks" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:Button ID="btnInsert" runat="server" onclick="btnInsert_Click" Text="Insert" CommandArgument="" CommandName=""/>
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click" Text="Update" CommandArgument="" CommandName=""/>
</form>
C# - Code behind...
protected void btnInsert_Click(object sender, EventArgs e)
{
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnect"].ConnectionString);
cn.Open();
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox Subject_Id = (TextBox)item.FindControl("Subject_Id");
TextBox Subject_Name = (TextBox)item.FindControl("Subject_Name");
TextBox Marks = (TextBox)item.FindControl("Marks");
SqlCommand cmd = new SqlCommand("Insert into result VALUES (id='"+#Subject_Id+"',name='"+#Subject_Name+"',marks='"+#Marks+"')", cn);
Repeater1.DataSource = cmd.ExecuteReader();
Repeater1.DataBind();
cn.Close();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
}
Now i want to insert that data into following table.....
result_table
id varchar(10)
name varchar(20)
marks varchar(3)
how can i perform insert and update function to retrieve data from to the database... with easy way ? ? thanks...
Implement the btnInsert_Click function with the following
** edited as per your new function
protected void btnInsert_Click(object sender, EventArgs e)
{
String connectionString = ConfigurationManager.ConnectionStrings["DbConnect"].ConnectionString;
String queryString = "";
using (SqlConnection connection = new SqlConnection(connectionString))
{
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox Subject_Id = (TextBox)item.FindControl("Subject_Id");
TextBox Subject_Name = (TextBox)item.FindControl("Subject_Name");
TextBox Marks = (TextBox)item.FindControl("Marks");
queryString = "Insert into result VALUES (id='"+#Subject_Id+"',name='"+#Subject_Name+"',marks='"+#Marks+"')";
SqlCommand command = new SqlCommand(queryString, connection);
// execute the query to update the database
cmd.ExecuteNonQuery();
}
}
//call the function to load the gridview if it is lost on postback.
}
It is always better to move the database and grid view filling codes to separate functions, so that it is easy to repeat the actions on button clicks.
insert some property in your button tags:
CommandArgument="" CommandName=""
Repeater1.ItemCommand +=new RepeaterCommandEventHandler(Repeater1_ItemCommand);
Create a function named protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e){ some code you want to write.........}
Dim permissionList As New List(Of OPASWCFApp.PROJECT_NOTE_CONTACT_MAP)
For Each rItem As RepeaterItem In rptProducts.Items
Dim qty1 As Integer
Dim qty2 As Integer
Dim hdnvalue As Integer
Dim txtBox1 As TextBox = DirectCast(rItem.FindControl("numAdmin1"), TextBox)
Dim txtBox2 As TextBox = DirectCast(rItem.FindControl("numAdmin2"), TextBox)
Dim hdnf As HiddenField = DirectCast(rItem.FindControl("hdnContacttype"), HiddenField)
qty1 = Convert.ToInt32(txtBox1.Text)
qty2 = Convert.ToInt32(txtBox2.Text)
hdnvalue = Convert.ToInt32(hdnf.Value)
If qty1 > 0 Or qty2 > 0 Then
Dim _d As OPASWCFApp.PROJECT_NOTE_CONTACT_MAP =
New OPASWCFApp.PROJECT_NOTE_CONTACT_MAP()
_d.PROJECT_NOTE_CONTACT_MAP_CONTACT_TYPE_ID = hdnvalue
_d.PROJECT_NOTE_CONTACT_MAP_DURATION = CInt((qty1 * 60) + qty2)
_d.PROJECT_NOTE_CONTACT_MAP_CONTACT_TYPE_ID = hdnvalue
permissionList.Add(_d)
End If
Next
ProcessDataResult.ContactMap = permissionList.ToArray()
Related
How can I save rows created in the list view in my database? How can I access the values in the (list view)? How to save the values created in the view list to the database?
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate runat="server">
<tr class="text-center">
<td class="product-remove"></td>
<td class="image-prod">
<div class="">
<asp:Image ID="Image1" CssClass=" img" ImageUrl='<%# "../img/" + Eval("picture" )%>' runat="server" />
</div>
</td>
<td class="product-name"><%# Eval("namebook") %> </td>
<td id="t_Plural" runat="server" class="price "><%# Eval("Price") %> </td>
<td class="quantity"><%# Eval("titel") %></td>
<td class="col-2">
<asp:Button ID="delete" CssClass="btn btn-outline-danger" CommandArgument='<%# Eval("id")%>' OnClick="delete_Click" runat="server" Text="حذف کالا" />
</td>
<td>
<%-- <input id="quantity2" runat="server" type="number" AutoPostBack="true" oninput="lod_gheymat" onserverclick="lod_gheymat" value="" min="1" max="20" />--%>
<asp:TextBox ID="quantity2" runat="server" CssClass="input-wrap" AutoPostBack="true" OnTextChanged="lod_gheymat" Text="1" min="1" max="20"></asp:TextBox>
</td>
<td >
<div class="row">
<asp:Label ID="lbl_Plural" runat="server" Text="0"></asp:Label> <span class="row"> تومان</span>
</div>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
The way to approach this type of issue and problem is to NOT try and add to the database from the list view.
What you do is get your data (say in a data table).
then send the data table to the list view.
Now, if you want say a "add new row" button?
Add the row to the data table, and then re-bind the list view.
Next up?
You asking how to add this to the database, but is not that where it came form in the first place?
and it is VERY confusing that you asking how to add rows to this LV, but how is the user going to add the picture?
Next up, how is this post getting up-votes? I will assume up-votes are not being messed with? I'll put this issue aside, but something not fitting here.
Ok, so, how to add rows, and how to save such rows back to the database?
You can achieve this goal this way:
First, we assume the LV can now be freely edit. That means using text boxes.
so, we have this markup:
(probably not HUGE important the LV you have, but the "idea" outlined here should work fine).
<style> .borderhide input, textarea {border:none}</style>
<div style="width:70%;padding:20px">
<h2>Fighter Prints</h2>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr style="">
<td><asp:TextBox ID="Fighter" runat="server" Text='<%# Eval("Fighter") %>' TextMode="MultiLine" /></td>
<td><asp:TextBox ID="Engine" runat="server" Text='<%# Eval("Engine") %>' TextMode="MultiLine" Width="200px" /></td>
<td><asp:TextBox ID="Thrust" runat="server" Text='<%# Eval("Thrust") %>' Width="70px" /></td>
<td><asp:TextBox ID="Description" runat="server" Text = '<%#Eval("Description") %>'
TextMode="MultiLine" Width="340px" Rows="5" /></td>
<td>
<asp:Image ID="iPreview" runat="server" Height="68px" Width="149px"
ImageUrl='<%# Eval("ImagePath") %>'/>
</td>
<td><asp:TextBox ID="Qty" runat="server" Text='<%# Eval("Qty") %>' style="width:30px;text-align:right"/></td>
<td><asp:TextBox ID="Price" runat="server" Text='<%# string.Format("{0:c2}",Eval("Price")) %>' style="Width:70px;text-align:right"/></td>
<td><asp:TextBox ID="Total" runat="server" Text='<%# string.Format("{0:c2}",Eval("Total")) %>' style="Width:70px;text-align:right" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server"
class="table table-hover borderhide ">
<tbody>
<tr runat="server" style="" >
<th runat="server">Fighter</th>
<th runat="server">Engine</th>
<th runat="server">Thrust (lbs)</th>
<th runat="server">Description</th>
<th runat="server">Preview</th>
<th runat="server" style="text-align:right">Qty</th>
<th runat="server" style="width:70px;text-align:right">Price</th>
<th runat="server" style="width:70px;text-align:right">Total</th>
</tr>
<tr id="itemPlaceholder" runat="server" />
</tbody>
<tfoot>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td><td>Total</td>
<td><asp:TextBox ID="MyTotal" runat="server" Text="0" Width="70px" Style="text-align:right"></asp:TextBox></td>
</tr>
</tfoot>
</table>
</LayoutTemplate>
</asp:ListView>
Ok, so the code to load is now this:
DataTable rstData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
Session["rstData"] = rstData;
}
else
rstData = Session["rstData"] as DataTable;
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
conn.Open();
rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
rstData.Columns.Add("Total", typeof(decimal),"[Qty] * [Price]");
ListView1.DataSource = rstData;
ListView1.DataBind();
decimal myTotal = 0;
foreach (ListViewItem OneRow in ListView1.Items)
{
TextBox MyPrice = OneRow.FindControl("Total") as TextBox;
myTotal += Decimal.Parse(MyPrice.Text, NumberStyles.Currency);
}
// now update the final total label
TextBox lblTotal = ListView1.FindControl("MyTotal") as TextBox;
lblTotal.Text = string.Format("{0:c2}", myTotal);
}
}
}
And now we have this:
Ok, for the above, note how we added 3 buttons below the LV.
And becuase I wanted "cute" icons in the buttons, I dropped in hteml buttons, not asp.net ones. But, with a "id" and runat=server, they work JUST the same anyway.
So, our 3 buttons are (right after the LV markup)
<div style="float:left">
<button id="cmdSave" runat="server" class="btn" onserverclick="cmdSave_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-save"></span>  Save
</button>
<button id="cmdUndo" runat="server" class="btn" style="margin-left:10px" onserverclick="cmdUndo_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-retweet"></span>  Un do
</button>
</div>
<div style="float:right">
<button id="cmdAddNew" runat="server" class="btn" onserverclick="cmdAddNew_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-new-window"></span>  Add New
</button>
</div>
Ok, so of the 3, the un-do button code is easy:
protected void cmdUndo_ServerClick(object sender, EventArgs e)
{
// undo changes - just re-load the lv
LoadGrid();
}
Ok, now the save button. This save button will:
save any new rows, and ALSO save any editing we do. Remember, since we used text boxes, then I can quite much tab around - edit ANY row. If I hit save, then we save all edits AND ALSO any new row added.
So, the save button does this:
protected void cmdSave_ServerClick(object sender, EventArgs e)
{
GridToTable(); // send lv to table
SaveToDatabase();
}
So, now we need the routine to send the LV to the table. That code is this:
void GridToTable()
{
// pull grid rows back to table.
foreach (ListViewItem rRow in ListView1.Items)
{
int RecordPtr = rRow.DataItemIndex;
DataRow OneDataRow;
OneDataRow = rstData.Rows[RecordPtr];
OneDataRow["Fighter"] = ((TextBox)rRow.FindControl("Fighter")).Text;
OneDataRow["Engine"] = ((TextBox)rRow.FindControl("Engine")).Text;
OneDataRow["Thrust"] = ((TextBox)rRow.FindControl("Thrust")).Text;
OneDataRow["Description"] = ((TextBox)rRow.FindControl("Description")).Text;
OneDataRow["Qty"] = ((TextBox)rRow.FindControl("Qty")).Text;
OneDataRow["Price"] = Decimal.Parse(((TextBox)rRow.FindControl("Price")).Text,
NumberStyles.Currency);
}
}
So, the above takes ANY edit - any row you edit, and send changes from LV->rstData.
So, now we need the rstData save all rows, all edits, all additions back to the database, and that code is this:
void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, now that is quite much all we need.
The last button, "add row" is also easy, and looks like this:
protected void cmdAddNew_ServerClick(object sender, EventArgs e)
{
// user might have done some editing, so, pull LV to table
// just in case
GridToTable();
// add new row to database
DataRow MyNewRow = rstData.NewRow();
// setup some defaults and values for this new row
//MyNewRow["DateCreate"] = DateTime.Now;
rstData.Rows.Add(MyNewRow);
ListView1.DataSource = rstData;
ListView1.DataBind();
}
That is it. So, if I am looking at above LV, and hit add-new, we now have this:
so I can just fill out the information, and then hit save. If I hit un-do, then the row will not be added (nor saved).
Note how we had a min of code to do the save. Note how we did not mess with a boatload of templates (and thus save world poverty).
So, this works really nice, was not a lot of code and the real secrets "idea" here was persisting the rstData. This allows great ease of adding new rows, but MORE important it was very simple then to send the edits back to the database, and that one save command will not only save any editing in the LV, but also will create the new rows in the database for you. So, you can quite much tab around in that lv - almost like excel. So we don't have a huge mess of "edit" buttons, and all that jazz. Just a simple grid of data, and a simple save, or add new button.
Note VERY careful how the GridToTable works. As this shows HOW to grab, and get values from the LV, and that was quite much the "major" part of your question. So, you can grab any row of the LV, but to pull values out of the one row, you have to use "FindControl".
protected void savetodatabase_Click(object sender, EventArgs e)
{
System.Web.UI.HtmlControls.HtmlGenericControl Labelid;
TextBox quantity2;
foreach (ListViewItem rRow in ListView1.Items)
{
itemlist iteml = new itemlist();
quantity2 = (TextBox)rRow.FindControl("quantity2");
Labelid = (System.Web.UI.HtmlControls.HtmlGenericControl)rRow.FindControl("Labelid");
iteml.quantity = quantity2.Text;
iteml.bookid = Convert.ToInt32(Labelid.InnerText) ;
iteml.Date = DateTime.Now;
iteml.userid = Convert.ToInt32(Session["userid"].ToString()) ;
DatabaseContext context = new DatabaseContext();
context.itemlists.Add(iteml);
context.SaveChanges();
}
}
Guys before asking this questions I did a lot of research on this topic but I am not able to detect the problem.I have radio button in the datalist and I am trying to get the selected radio button value.But it is showing me false for all radio button on submit button.My datalist is like this:
<asp:DataList ID="dlEmails" RepeatLayout="Flow" runat="server" >
<HeaderTemplate>
<table>
<tr>
<th>Select Email Address </th>
<th>Status</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:RadioButton ID="rbtnSelect" Text='<%#Eval("Emails") %>' onclick='fnrad(this);' GroupName="a" Checked='<%#Eval("Primary") %>' runat="server" /><br />
(<asp:Label ID="lablel" runat="server" Text='<%#Eval("Verified") %>'> </asp:Label>)
</td>
<td valign="middle">
<asp:Label ID="lblID" Style="display: none;" runat="server" Text='<%#Eval("Id") %>'> </asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Main") %>'> </asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
Javascript for allowing only single radio button selection at a time is like this:
<script>
function fnrad(rbtn) {
var radioList = document.getElementsByTagName("input");
for (var i = 0 ; i < radioList.length; i++) {
if (radioList[i].type == "radio") {
radioList[i].name = 'a';
radioList[i].checked = false;
}
}
rbtn.checked = true;
rbtn.setAttribute("Checked","checked");
}
</script>
And my code behind is like this:
public partial class Member_EmailList : System.Web.UI.Page
{
EmailsBAL _mbl = new EmailsBAL(SessionContext.SystemUser);
DataSet _ds = new DataSet();
URLMessage URLMessage = new URLMessage();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
_mbl.LoadByUser(_ds, 1);//SessionContext.SystemUser;
dlEmails.DataSource = _ds.Tables[_mbl.SqlEntityX];
dlEmails.DataBind();
}
protected void lnkConfirm_Click(object sender, EventArgs e)
{
RadioButton rb;
Label lbl;
int id = 0;
foreach (DataListItem di in dlEmails.Items)
{
rb = (RadioButton)di.FindControl("rbtnSelect");
if (rb.Checked == true)
{
lbl = (Label)di.FindControl("lblID");
id = WebHelper.Cast(lbl.Text, 0);
}
}
//Response.Redirect("~/Member/ConfirmEmail.aspx?" + URLMessage.Encrypt("SystemUser=" + SessionContext.SystemUser + "Id=" + id.ToString()));
}}
I tried your javascript function and experienced your problem
I would like to suggest to use Jquery on your javascript function. I refactored your jav fuction to this.
function fnrad(rbtn) {
$('input').removeAttr('checked');
$(rbtn).prop('checked', true);
}
This works perfectly on my end. Please let me know if you still encountering the issue.
I have a Datatable that has a checkbox and a value, What I want is that when I click a button it would get all the checked boxes and their corresponding value and Add them to a blank Datatable. I not planning to save the data moved from 1 list to another, as there will be another functionality to confirm if I want to save the changes(not being asked in this question).
This is my html code:
<asp:ListView runat="server" ID="uoListViewAirportSaved" EmptyDataText="No Data Found">
<LayoutTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="500px">
<tr>
<th runat="server"> </th>
<th runat="server">Airport</th>
</tr>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td class="leftAligned">
<asp:CheckBox ID="uoCheckBoxSelect" runat="server" />
</td>
<td class="leftAligned">
<asp:HiddenField ID="uoHiddenFieldAirport" runat="server" Value='<%# Eval("ColAirportCodeVarchar") %>' />
<asp:Label ID="uoLabelAirport" runat="server" Text='<%# Eval("colAirportFullName")%>' />
</td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="500px">
<tr>
<td>Airport</td>
</tr>
<tr>
<td colspan="3" class="leftAligned">No Record</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:ListView>
And the code when I click the add button:
private void AddAirport() {
CheckBox uoCheckBoxSelect;
HiddenField uoHiddenFieldAirport;
Label uoLabelAirport;
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
string serviceProvider = GlobalCode.Field2String(Request.QueryString["pid"]);
///datatable with all list of airports
dt = VendorMaintenanceBLL.GetServiceProviderAirportbyBrand(serviceProvider);
///datatable with provider's current airports
dt2 = VendorMaintenanceBLL.GetServiceProviderAirportbyVendor(serviceProvider);
foreach(ListViewItem item in uoListViewAirport.Items)
{
uoCheckBoxSelect = (CheckBox)item.FindControl("uoCheckBoxSelect");
if (uoCheckBoxSelect.Checked == true)
{
uoHiddenFieldAirport = (HiddenField)item.FindControl("uoHiddenFieldAirport");
uoLabelAirport = (Label)item.FindControl("uoLabelAirport");
/// my new list should contain the values from the checked values of the checkboxes
???
}
}
}
My Datatable contains the AirportID and the AirportStringName columns.
I found a code that I'm trying to replicate, logic-wise. However it is designed for a list:
List<AirportDTO> listToBeAdded = new List<AirportDTO>();
List<AirportDTO> listAdded = new List<AirportDTO>();
listToBeAdded = GetAirportNotInUser(false, false);
listAdded = GetAirportInUser(false);
foreach (ListViewItem item in uoListViewAirport.Items)
{
uoCheckBoxSelect = (CheckBox)item.FindControl("uoCheckBoxSelect");
if (uoCheckBoxSelect.Checked == true)
{
uoHiddenFieldAirport = (HiddenField)item.FindControl("uoHiddenFieldAirport");
uoLabelAirport = (Label)item.FindControl("uoLabelAirport");
var listToAdd = (from a in listToBeAdded
where a.AirportIDString == GlobalCode.Field2String(uoHiddenFieldAirport.Value)
select new
{
AirportID = a.AirportIDString,
AirportName = a.AirportNameString,
}).ToList();
}
}
I do not know how I would get the necessary data from the datatable as it is different from a list. Is there a way for me to do the same thing with DataTables the way lists were tackled.
Since I really need to fix the problem yesterday, I decided to do the following.
What I did was just basic for loop, then inside compare each row and then just use Datatable.ImportRow and DataTable.RemoveAt. I also added a temporary Datatable for the changed lists.
foreach(ListViewItem item in uoListViewAirport.Items)
{
uoCheckBoxSelect = (CheckBox)item.FindControl("uoCheckBoxSelect");
if (uoCheckBoxSelect.Checked == true)
{
uoHiddenFieldAirport = (HiddenField)item.FindControl("uoHiddenFieldAirport");
uoLabelAirport = (Label)item.FindControl("uoLabelAirport");
string HiddenFieldAirport = GlobalCode.Field2String(uoHiddenFieldAirport.Value);
for (var f = 0; f < dt.Rows.Count; f++ )
{
if (dt.Rows[f]["colAirportIDInt"].ToString() == HiddenFieldAirport)
{
dt3.ImportRow(dt.Rows[f]);
dt.Rows.RemoveAt(f);
}
}
}
}
The code is dirty, plus I had to sort it as well, but since I really needed it, I can make do with this.
I have a store procedure
create proc spAddEmployees
#Name varchar(50),
#Gender varchar(10),
#Salary int,
#EmployeeId int out
as
begin
insert into tblEmployees values (#Name, #Gender, #Salary)
select EmployeeId = SCOPE_IDENTITY()
end
which has an output parameter that tells the user the current scope_identity
The markup looks like
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table style="border: 1px solid black; font-family:Arial">
<tr>
<td>
Employee Name
</td>
<td>
<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Gender
</td>
<td>
<asp:DropDownList ID="ddlGender" runat="server">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Salary
</td>
<td>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
</table>
And the code behind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//read from the config file so you don't have to hardcode the connection string
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
//when you use the using statement the database connection is automatically closed for you
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spAddEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", txtEmployeeName.Text);
cmd.Parameters.AddWithValue("#Gender",ddlGender.SelectedValue);
cmd.Parameters.AddWithValue("#Salary", txtSalary.Text);
SqlParameter outputParmeter = new SqlParameter();
outputParmeter.ParameterName = "#EmployeeId";
outputParmeter.SqlDbType = SqlDbType.Int;
outputParmeter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outputParmeter);
con.Open();
cmd.ExecuteNonQuery();
string EmpId = outputParmeter.Value.ToString();
lblMessage.Text = "Employee Id = " + EmpId;
}
}
}
This program should add a new row to the tblEmployees table and then output to the user the output parameter of the stored procedure. It runs and adds the row to the number when the button is clicked, but the output parameter isn't being printed to the screen. Thoughts?
Perhaps:
select EmployeeId = SCOPE_IDENTITY()
In the stored procedure should be:
select #EmployeeId = SCOPE_IDENTITY()
The syntax in the stored procedure isn't right.
You should use
select #EmployeeId = SCOPE_IDENTITY()
^
and also the usual way to retrieve the output parameter is through the command collection. I am not sure that in the process the parameter is replaced somewhere
string EmpId = cmd.Parameters["#EmplyeeId"].Value.ToString();
I have a DropDownList inside in ListView..
I wanted to get a data when command clicked.
this is my code..
protected void ListView2_ItemCommand(object sender, ListViewCommandEventArgs e){
string shipmethod = ((DropDownList)e.Item.FindControl("ShippingComapnyDDL")).SelectedValue;
}
but it always return null value..
I've googling about 3 hours, and try many function..
but still cant solve this bug..
please help me guys,
UPDATE
here's my aspx page
<asp:DropDownList ID="ShippingComapnyDDL" runat="server" SelectedValue='<%# Eval("ShippingCompany") %>'>
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="FedEx" Value="FedEx"></asp:ListItem>
<asp:ListItem Text="UPS" Value="UPS"></asp:ListItem>
<asp:ListItem Text="Other" Value="Other"></asp:ListItem>
</asp:DropDownList>
DO you have headers set?try
if(e.Item.ItemIndex!=-1)
{
string shipmethod = ((DropDownList)e.Item.FindControl("ShippingComapnyDDL")).SelectedValue;
}
if not working then try
string shipmethod = (e.Item.FindControl("ShippingComapnyDDL") as DropDownList).SelectedValue;
Please try
<%#DataBinder.Eval(Container.DataItem,"ShippingCompany")%>
instead of
<%#Eval("ShippingCompany")%>
For more details:
http://aspadvice.com/blogs/joteke/archive/2008/08/24/Is-_2200_Databinding-methods-such-as-Eval_280029002C00_-XPath_280029002C00_-and-Bind_28002900_-can-only-be-used-in-the-context-of-a-databound-control_2E002200_-causing-you-grief_3F00_.aspx
try this:
DropDownList ddl = (DropDownList)e.Item.FindControl("ShippingComapnyDDL");
if (ddl != null)
{
//code here
}
<asp:ListView ID="lvwCoreConfigureData" runat="server" DataKeyNames="Course_Config_Id" OnItemCommand="lvwCore_Config_ItemCommand" OnItemDataBound="lvwCore_Config_ItemDataBound">
<LayoutTemplate>
<table class="table mobile-stacked mb-0">
<thead>
<tr role="row">
<th style="width: 240px">
<asp:Label runat="server" Text="<%$Lang:Resource.Core_Config_Course %>"></asp:Label>
</th>
</tr>
</thead>
<tbody>
<tr runat="server" id="itemPlaceholder" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr role="row">
<td data-th="Name">
<asp:DropDownList ID="ConfigCourseName" runat="server" AutoPostBack="true" CssClass="form-control" OnSelectedIndexChanged="ConfigCourseName_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
2 . This methos will be provide data binding to dropdown while edit mode
protected void lvwCore_Config_ItemDataBound(Object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item; // load one row item
var CourseId = ((Edulearn.Model.CoreProgramme.CoreProgrammeConfigrationDM)dataItem.DataItem).CourseId; //
DropDownList ConfigCourseName = (e.Item.FindControl("ConfigCourseName") as DropDownList);
ConfigCourseName.DataSource = CoreProgrammeRepository.GetCoreProgrammeCourseList(TimeZoneId, new { Name = "TEST" }); // Get the data to dropdown (all data)
ConfigCourseName.DataTextField = "Name"; // assign here which one need to display
ConfigCourseName.DataValueField = "CourseId"; // assign here which one is the value for database save
ConfigCourseName.DataBind(); // bind the data
ConfigCourseName.SelectedValue = CourseId.ToString(); // Here selected values from database will be added
ConfigCourseName.Items.Insert(0, new ListItem("Please select")); // Default value only for display
}
}