I have two dropdown list named dl_bankName,dl_branch and a textbox named txt_bankCode.dl_bankName will be filled on pageLoad and dl_branch will get filled on the selectedIndexChange of dl_bankName and txt_bankCode will be filled on the selectedIndexChange of dl_branch. dl_bankName is filled and the selected value is retained even after postBack but dl_branch name is changed to the first value when we select other values.
my sample code is given below
HTML
<asp:DropDownList ID="dl_bankName" runat="server" Width="230px"
Height="22px" AutoPostBack="True" onselectedindexchanged="dl_bankName_SelectedIndexChanged"> </asp:DropDownList>
<asp:DropDownList ID="dl_BranchName" Width="230px" Height="22px" runat="server"
onselectedindexchanged="dl_BranchName_SelectedIndexChanged"
AutoPostBack="True"></asp:DropDownList>
<asp:TextBox ID="txt_IfscMicr" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="txt_IfscMicr" runat="server" ID="RequiredFieldValidator9" ErrorMessage="*" Font-Size="Large" ForeColor="#FF5050" />
CODE
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
filldl_bankName();
}
}
protected void dl_bankName_SelectedIndexChanged(object sender, EventArgs e)
{
if (dl_BranchName.DataSource == null)
{
filldl_BranchName();
}
txt_IfscMicr.Text = "";
}
protected void dl_BranchName_SelectedIndexChanged(object sender, EventArgs e)
{
filltxt_IfscMicr();
}
protected void filldl_bankName()
{
string query = "select '--Select--' as bank_name,'0' as bank_code from DUAL union all select distinct(bank_name),bank_code from em_bank_details ";
dl_bankName.DataSource = GetDt(query);
dl_bankName.DataTextField = "bank_name";
dl_bankName.DataValueField = "bank_code";
dl_bankName.DataBind();
}
protected void filldl_BranchName()
{
string query = "select '--Select--' as branch_name,'0' as bank_code from DUAL union all select distinct(branch_name),bank_code from em_bank_details where bank_name='" + dl_bankName.SelectedItem.Text + "'";
dl_BranchName.DataSource = GetDt(query);
dl_BranchName.DataTextField = "branch_name";
dl_BranchName.DataValueField = "bank_code";
dl_BranchName.DataBind();
}
protected void filltxt_IfscMicr()
{
string query = "select distinct(branch_code),bank_code from em_bank_details where bank_name='" + dl_bankName.SelectedItem.Text + "' and branch_name='" + dl_BranchName.SelectedItem.Text + "'";
txt_IfscMicr.Text = GetDt(query).Rows[0]["branch_code"].ToString();
}
I've solved the issue by commenting the code line
dl_BranchName.DataValueField = "bank_code";
in the function filldl_BranchName() . The bank_code was all same for all the branch_name maybe that's what cause the issue .Now everything is working as per my requirement.
Related
i'm trying to do a display database's item(tables, rows, fk,...).
I'm stucking at first few step. I loaded the db's names into a DropDownList. But i tried to load Tables from Selected db's name into CheckBoxList but it shows nothing.
Here are my codes
aspx:
<form id="form1" runat="server" method="get">
<div>
<asp:DropDownList ID="drpListDBName" runat="server" OnSelectedIndexChanged="drpListDBName_SelectedIndexChanged">
</asp:DropDownList>
</div>
<div>
<asp:CheckBoxList ID="chkListTable" runat="server">
</asp:CheckBoxList>
</div>
aspx.cs:
public static String dbname = "";
protected void Page_Load(object sender, EventArgs e)
{
String query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution'";
Program.Connect();
if(!Page.IsPostBack)
{
drpListDBName.DataSource = Program.ExecSqlDataReader(query);
drpListDBName.DataTextField = "name";
drpListDBName.DataBind();
}
}
protected void drpListDBName_SelectedIndexChanged(object sender, EventArgs e)
{
dbname = drpListDBName.SelectedValue.Trim();
String query = "USE " + dbname +
" SELECT * FROM SYS.tables" +
" WHERE is_ms_shipped = 0";
Program.Connect();
if (chkListTable.Items.Count > 0)
chkListTable.Items.Clear();
chkListTable.DataSource = Program.ExecSqlDataReader(query);
chkListTable.DataTextField = "name";
chkListTable.DataBind();
Response.Write(chkListTable);
}
I'm still new to asp.net. Thanks in advance.
Ok, while you could send your 2nd selection (the list of tables) to a check box list?
(and if you needing to select multiple tables - perhaps yes).
but, lets do one better. Lets use two combo boxes. First one, select database, fill 2nd combo box with tables.
Then you select a table, and display the table in a grid.
So, first up is (possbile) is the connection string used. We can assume that you built or setup at least one working connection string to one of the databases on that sql server.
So, project->"my project name settings".
You get this:
So, I have a few already made, but note the [...] button, if you click on that, then VS will launch a connection builder for you (nice and easy). And you can test the connection.
So, we just start out by using TEST4. (note that this DOES put the connection string automatic in web config for you).
Ok, So lets drop in a combo box (to select database).
And then our check box list.
So, we have this markup:
<h4>Select Database</h4>
<asp:DropDownList ID="DropDownList1" runat="server" Width="177px"
DataTextField="name"
DataValueFeild="name"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataTextField="TABLE_NAME"
DataValueField="TABLE_NAME" >
</asp:CheckBoxList>
And now we have this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
Session["MyCon"] = Properties.Settings.Default.TEST4;
string query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution' ORDER BY Name";
DropDownList1.DataSource = MyRst(query);
DropDownList1.DataBind();
}
public DataTable MyRst(string strSQL)
{
var rst = new DataTable();
using (SqlConnection conn = new SqlConnection((Session["MyCon"] as string)))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rst.Load(cmdSQL.ExecuteReader());
}
}
return rst;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// set connecting string from TEST4 to whatever database selected
string strCon = Session["MyCon"] as string;
string strDB = DropDownList1.SelectedItem.Value;
strCon = strCon.Replace("Initial Catalog = test4;", strDB);
Session["MyCon"] = strCon;
// now load check box list with all tables
string strSQL = #"SELECT TABLE_NAME FROM [" + strDB + "].INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
CheckBoxList1.DataSource = MyRst(strSQL);
CheckBoxList1.DataBind();
}
So, now we get this:
So, yes, you can set a datatable to check box list. But, some of my databases have quite a few tables - too long (many) check boxes.
So, lets change our code to two combo boxes.
However, we need a "please select" for the combo boxes.
So, our mark up is now this:
<h4>Select Database</h4>
<asp:DropDownList ID="DropDownList1" runat="server" Width="180px"
DataTextField="name"
DataValueFeild="name"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<h4>Select Table</h4>
<asp:DropDownList ID="DropDownList2" runat="server" Width="180"
DataTextField="TABLE_NAME"
DataValueField="TABLE_NAME"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged"
>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" CssClass="table">
</asp:GridView>
Our code is now this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
Session["MyCon"] = Properties.Settings.Default.TEST4;
string query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution' ORDER BY Name";
DropDownList1.DataSource = MyRst(query);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Please Select", ""));
}
public DataTable MyRst(string strSQL)
{
var rst = new DataTable();
using (SqlConnection conn = new SqlConnection((Session["MyCon"] as string)))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rst.Load(cmdSQL.ExecuteReader());
}
}
return rst;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// set connecting string from TEST4 to whatever database selected
string strCon = Session["MyCon"] as string;
string strDB = DropDownList1.SelectedItem.Value;
strCon = strCon.Replace("Initial Catalog = test4;", strDB);
Session["MyCon"] = strCon;
// now load 2nd cbo box list with all tables
string strSQL = #"SELECT TABLE_NAME FROM [" + strDB + "].INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
DropDownList2.DataSource = MyRst(strSQL);
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("Please Select", ""));
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
// send results to the Grid
string strSQL = "SELECT * FROM [" + DropDownList2.SelectedItem.Value + "]";
GridView1.DataSource = MyRst(strSQL);
GridView1.DataBind();
}
And now we get this:
So, I used a working connection string to a given database. I quite much assumed that the same information could and would connect to all of them, so I swap out TEST4 database name with any one we select.
I'm adding a value database table then i want to show on DropDownList. This code working when page is loading. But when i add new value to db, dropdownlist doesn't update. I called after adding value but doesn't change. When i don't use !IsPostBack, dropdownlist updating but in this case DataValueField doesnt working.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
.............
listStudent.DataSource = dt;
listStudent.DataTextField = "st";
listStudent.DataValueField = "id";
listStudent.DataBind();
}
Well, you are free to put the DataTextField and the DataValue field in the markup.
(but does not matter one bit at all).
So, say we have this markup:
(drop down, and a button to add a new value).
<asp:DropDownList ID="cboHotels" runat="server"
DataValueField="HotelName" DataTextField="HotelName" AutoPostBack="True" Width="174px" >
</asp:DropDownList>
<asp:Button ID="cmdAdd" runat="server" Text="+" style="margin-left:10px"
OnClick="cmdAdd_Click"
OnClientClick="return AddHotel();" />
<asp:TextBox ID="txtHotelName" runat="server" ClientIDMode="Static" style="display:none"></asp:TextBox>
<script>
function AddHotel() {
myhotel = prompt("Enter New Hotel Name")
if (myhotel != null) {
document.getElementById('txtHotelName').value = myhotel
return true
}
else {
return false
}
}
</script>
So, we have that "+" button beside the drop to add a new row to the database.
So, our code to fill the drop down looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
LoadCombo();
}
public void LoadCombo()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT HotelName from tblHotels ORDER BY HotelName",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
cboHotels.DataSource = cmdSQL.ExecuteReader();
cboHotels.DataBind();
// add a blank (no select row)
cboHotels.Items.Insert(0, new ListItem(""));
}
}
And our code to add a new row looks like this:
protected void cmdAdd_Click(object sender, EventArgs e)
{
// add a new hotel to table
using (SqlCommand cmdSQL =
new SqlCommand("INSERT into tblHotels (HotelName) Values(#Hotel)",
new SqlConnection(Properties.Settings.Default.AccessDB)))
{
cmdSQL.Connection.Open();
cmdSQL.Parameters.Add("#Hotel", SqlDbType.NVarChar).Value = txtHotelName.Text;
cmdSQL.ExecuteNonQuery();
}
LoadCombo(); // re-load combo to show new row
// lets be nice and select the row we just added
cboHotels.ClearSelection();
cboHotels.Items.FindByText(txtHotelName.Text).Selected = true;
}
And we get this:
I have gridview and some textbox that user can search .
when user search I updated gridview but when changed pageing I bind gridview again and I lost search result .
how can I change gridview paging without call DataBind Again?
I used this for Paging:
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
TicketDataBinding();
}
and my search method is :
protected void btn_search_Click(object sender, EventArgs e){
using (var ticket = new BLL.Ticket())
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
grv_Data.DataBind();
}}
sorry I forgot asp.net webform and I dont know how do this ?
I've included two examples of binding data to a GridView where paging still works on filtered data. I hope it helps you.
1.You can do this completely in .ASPX:
<form id="form1" runat="server">
<asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" DataSourceID="sqlDS" AllowPaging="true" PageSize="5" AutoGenerateColumns="true">
<Columns>
<asp:BoundField DataField="EmailType" />
<asp:BoundField DataField="EmailAddress" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlDS"
runat="server"
ConnectionString="<%$ ConnectionStrings:conn %>"
SelectCommand="SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'">
<SelectParameters>
<asp:ControlParameter ControlID="txtEmailAddress" DbType="String" Name="EmailAddressParam" DefaultValue="%" />
</SelectParameters>
</asp:SqlDataSource>
</form>
2.Or in code behind:
public partial class PagingAndSearchingInGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.GetData();
}
private void GetData()
{
string emailAddress = txtEmailAddress.Text;
DataTable table = !Page.IsPostBack ? GetEmails() : GetEmails(emailAddress);
GridView1.DataSource = table;
GridView1.DataBind();
}
private DataTable GetEmails(string emailAddress = "%")
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'", connection))
{
command.Parameters.AddWithValue("#EmailAddressParam", emailAddress);
using (var a = new SqlDataAdapter(command))
{
connection.Open();
a.Fill(table);
connection.Close();
}
}
}
return table;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.GetData();
}
}
While the pageIndex changed event, you can check whether the search button is already clicked or not. When clicking the search button you can set a hiddenfield value to 1 or something like that.
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
if(status==1) //Search button is already clicked, means the grid contains searched result
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
}
else
{
//Search button is not clicked .. means the grid contains all records.
TicketDataBinding();
}
}
I'm having trouble returning to listview and cancelling the edit of items using ASP and C#.
I already have the same answer as this
but I'm still getting the error message of Cancel can only be called from the currently-edited record or an insert item.
Here is the offending code - any pointers on what is causing this would be very useful:
I also have a layout, selected template, and insert which are all identical.
<asp:ListView ID="ListView1" runat="server" DataSourceID="sqlDatasource1"
EnableViewState="true" DataKeyNames="EndUserId" AllowPaging="True"
OnItemCommand="ListView1_ItemCommand" OnItemCanceling="ListView1_ItemCanceling">
<EditItemTemplate>
<tr>
<asp:Label runat="server" ID="tbId" Text='<%#Eval("EndUserId") %>' Visible="false" />
<td>
<asp:TextBox runat="server" ID="tbEmail" Text='<%#Eval("Email") %>' />
</td>
<td>
<asp:TextBox runat="server" ID="tbRole" Text='<%#Eval("Role") %>' />
</td>
<td>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
c# backend controlling
protected void ListView1_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
ListView1.EditIndex = -1;
ListView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
if (!IsPostBack)
{
}
}
added backend
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
Label tbId = (Label)e.Item.FindControl("tbId");
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string updateCommand =
"UPDATE [EndUser_tbl] SET [Email]='" +
tbEmail.Text + "', [Password]='" + tbPass.Text +
"'WHERE EndUserId=" + Convert.ToInt32(tbId.Text) + ";";
sqlDatasource1.UpdateCommand = updateCommand;
}
if (e.CommandName == "Delete")
{
Label id = (Label)e.Item.FindControl("tbId");
string deleteCommand = "DELETE FROM [EndUser_tbl] " +
"WHERE EndUserId=" + Convert.ToInt32(id.Text);
sqlDatasource1.DeleteCommand = deleteCommand;
}
if (e.CommandName == "Insert")
{
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string insertCommand = "INSERT INTO [EndUser_tbl] " +
"([Email],[Password],[ContractRef],[Role])" +
"VALUES ('" + tbEmail.Text + "','" + tbPass.Text +
"','" + tbPass.Text + "');";
sqlDatasource1.InsertCommand = insertCommand;
}
}
Change the Page_load like this way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
}
}
And try it again.
I cant seem to pass my variable through to the next page. Can anyone tell me what i am doing wrong?
var finalValue = value * sqlCouponValue;
finalValue = Math.Round(finalValue, 2);
Session["discountedOrderTotal"] = finalValue.ToString();
where i am trying to call it again on the next page:
e.Row.Cells[4].Text = "$" + Session["discountOrderTotal"];
Does anyone have any ideas? I have never used session variables before and am not sure why it is just returning a $. Any help would be much appreciated. Thanks!
you have different names. discountedOrderTotal vs discountOrderTotal
The first thing you should be careful is the name of the session. It should be same and when you are retrieving the session then you need to specify the type because it returns an object. So try this when you call this to next page
e.Row.Cells[4].Text = "$" + Session["discountedOrderTotal"].ToString();
public partial class Approve : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Convert.ToString(Session["id"]);
Label3.Text = Convert.ToString(Session["name"]);
}
protected void Button1_Click(object sender, EventArgs e)
{
int id1=Convert.ToInt32(Session["id"]);
TransferDAL dalob = new TransferDAL();
int x = dalob.updateapprove(id1);
Response.Redirect("View.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
int id1 = Convert.ToInt32(Session["id"]);
TransferDAL dalob = new TransferDAL();
int r = dalob.updatereject(id1);
Response.Redirect("View.aspx");
}
}
public partial class View : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
List<TransferBO> List2 = new List<TransferBO>();
TransferDAL obj1 = new TransferDAL();
List2 = obj1.view();
Gridview1.DataSource = List2;
Gridview1.DataBind();
}
}
protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow SelectedRow = Gridview1.SelectedRow;
Label id1 = (Label)SelectedRow.FindControl("Label1") as Label;
int id2 = Convert.ToInt32(id1.Text);
Label id3 = (Label)SelectedRow.FindControl("Label3") as Label;
string id4 = Convert.ToString(id3.Text);
Session["id"] = id2;
Session["name"] = id4;
Response.Redirect("Approve.aspx");
}
}
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Table ID="Table1" runat="server">
<asp:TableRow>
<asp:TableCell>Transfer Request ID</asp:TableCell>
<asp:TableCell> <asp:Label ID="Label1" runat="server" Text='<%# Eval("TransferRequestId") %>'></asp:Label></asp:TableCell>
<asp:TableCell></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>Employee Name</asp:TableCell>
<asp:TableCell> <asp:Label ID="Label3" runat="server" Text='<%# Eval("EmployeeName") %>'></asp:Label></asp:TableCell>
<asp:TableCell></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell><asp:Button ID="Button1" runat="server" Value="APPROVE" Text="Approve" OnClick="Button1_Click"></asp:Button></asp:TableCell>
<asp:TableCell><asp:Button ID="Button2" runat="server" value="REJECT" Text="Reject" Onclick="Button2_Click"></asp:Button></asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Content>