How to disable function onclick programmatically button - javascript

this is my programmatically button, there is the error null pointer exception in logcat.
This is my way to loop the button.But the disable button for the button cannot function.When i click on "save" button the programmatically button will disable. is it my way to disable button is incorrect?
String CountQuery = "SELECT * FROM Category";
db = new DBController(getActivity());
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cursor1 = db2.rawQuery(CountQuery, null);
{
int num = cursor1.getCount();
Button[] valueB = new Button[num];
for (int i = 1; i < num; i++) {
String SelectQuery = "SELECT * FROM Category where CategoryID='" + i + "'";
db = new DBController(getActivity());
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor cursor = db1.rawQuery(SelectQuery, null);
if (cursor.moveToNext()) {
String categoryName = cursor.getString(1);
String coordinateX = cursor.getString(2);
String coordinateY = cursor.getString(3);
valueB[i] = new Button(getActivity());
valueB[i].setText("" + categoryName);
valueB[i].setId(i);
valueB[i].setOnTouchListener(this);
params = new RelativeLayout.LayoutParams(300, 100);
params.leftMargin = Integer.parseInt(coordinateX);
params.topMargin = Integer.parseInt(coordinateY);
final int finalI = i;
valueB[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "asdasd" + finalI, Toast.LENGTH_SHORT).show();
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
viewPager.setCurrentItem(finalI);
}
});
mRrootLayout.addView(valueB[i],params);
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i[0] = 1; i[0] < num; i[0]++) {
valueB[i[0]].setOnTouchListener(null);
}
}
});
}
}

You can disable the onclick listener by using valueB[i].setOnClickListener(null);

you can disable the button by using setClickable method.
valueB[i].setClickable(false);
or you can user setEnabled method also like
valueB[i].setEnabled(false);

Related

How to send an object array from c# to javascript?

Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. When the data arrives to the view it is no longer the array i need to use.
This is the class:
public class Empresa
{
public string nombre { get; set; }
public int vidID { get; set; }
public string img64 { get; set; }
public string color { get; set; }
}
At the end the object will be something like this:
The object is send to the view and this is the output:
I have already tried with JsonConvert.SerializeObjectas i found on other threads, yet it doesnt seems to work. I tried to convert the data send with this jQuery.parseJSON(data) (Left) and with this JSON.parse(data)(Right); it throws an error on both cases as seen in the picture below.
I'm not sure if it is that way because the object sended is made this way:
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
var data = new List<Empresa>
{
new Empresa{nombre ="Globex Corp",color="red",vidId=1, img="data:image/jpeg;base64,blabla" },
new Empresa{nombre ="AM",color="blue",vidId=2, img="data:image/jpeg;base64,blabla" }
}
for(int i = 0; i<=6; i++)
{
_ar1.TryAdd(data[i].vidID, data[i]);
}
This is inside other function but it is the next one that involves the data send.
public IEnumerable<Empresa> GetArreglo()
{
return _ar1;
}
So far im not sure what could be wrong or if i need to aproach a different solution.
If any more info is needed ill post it. And even it is obvious im a newby still learning on this.
EDIT:
This is all the code involved:
// This is the JS
<script>
var ubi = '#ViewBag.ubicacion';
console.log("UbicaciĆ³n: " + ubi);
var conex = $.connection.channel;
var $marco = $('#marco');
var $imagen = $('#imagen');
var $empresa = $('#empresa');
function empezar() {
var min;
var max;
var pos;
var arreglo = new Array;
function init() {
conex.server.createGroup(ubi);
console.log("Entro al canal");
arreglo = conex.server.getArreglo(ubi);
//pos = arreglo.split('|');
//a.split is not a function
console.log(arreglo);
//console.log(pos);
setInterval(update, 6000);
}
function update() {
}
$.connection.hub.start().done(init);
}
window.onload = function() { empezar(); }
</script>
//It gets the conection to the HUB:
[HubName("channel")]
public class CanalHub : Hub
{
private readonly Canal _canal;
public CanalHub() : this(Canal.Instance) { }
public CanalHub(Canal canal)
{
_canal = canal;
}
public string[] GetArreglo(string ubi)
{
string[] array = _canal.GetArreglo(ubi);
return array;
//it is now a string[] because i wanted to
//try creating the obj with .split('|')
}
// And finally this is the last part involved:
public class Canal
{
private static Random random = new Random();
private volatile List<Canales> listaCan = new List<Canales>();
private readonly static Lazy<Canal> _instance = new Lazy<Canal>(() => new Canal(GlobalHost.ConnectionManager.GetHubContext<CanalHub>().Clients));
private readonly ConcurrentDictionary<int, Empresa> _datos = new ConcurrentDictionary<int, Empresa>();
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
private Canal(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
//Create the sample objects for the class
var datos = new List<Empresa>
{
new Empresa{nombre="Globex Corp", color="#A87F3D", vidID=1, img="balbal" },
new Empresa{nombre="AM", color="#535E89", vidID=2, img="balba" },
new Empresa{nombre="Frutijugos", color="#92191A", vidID=3, img="askldj" }
};
for (int i = 0; i <=6 ; i++)
{
_ar1.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 7; i <= 13; i++)
{
_ar2.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 14; i <= 20; i++)
{
_ar3.TryAdd(datos[i].vidID, datos[i]);
}
//sort them on 3 different arrays
}
private IHubConnectionContext<dynamic> Clients { get; set; }
public static Canal Instance
{
get { return _instance.Value; }
}
public string[] GetArreglo(string ubi)
{
string[] array = new string[7];
int i = 0;
if (ubi == "Campanario")
{
foreach (var item in _ar1)
{
array[i] += item.Value.nombre + "|";
array[i] += item.Value.color + "|";
array[i] += item.Value.img + "|";
array[i] += item.Value.vidID + "|";
i++;
}
return array;
}
//sort the array values and add them to the array
else return null;
}
It appears that your javascript promise is not set up correctly. The object in the view is the promise object and not the object returned. You are going to need to set up the promise correctly. deferred promise

Code keeps running without proper sequence of input

In the OnClickListener, addFood needs the date and time input from the datepicker fragment.
How can i make it wait till the input is done by the user?
Button breakfastAdd = findViewById(R.id.breakFastButton);
breakfastAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (breakfastSearch.getCount() == 0) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.emptySelectionLayout));
TextView text = layout.findViewById(R.id.toastText);
text.setText(R.string.selectedIsEmpty);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Log.d("list is", "empty");
} else {
new datePickerFragment().show(getSupportFragmentManager(), "datePicker");
addFood(context, breakfastDate, breakfastSearch, 1);
}
}
});
You should call your addFood(context, breakfastDate, breakfastSearch, 1); as an onChange in datePickerFragment instead.
You can put this code in you OnClickListener it will create DatePickerDialog and you will get date after you can put rest of the code:
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
int getMonth = month + 1;
int getDay = dayOfMonth;
String setMonth;
String setDay;
if (getMonth < 10)
setMonth = "0" + String.valueOf(getMonth);
else
setMonth = String.valueOf(getMonth);
if (getDay < 10)
setDay = "0" + String.valueOf(getDay);
else
setDay = String.valueOf(getDay);
String getDate = setMonth + "/" + setDay + "/" + year;
//You have date which user picked here you can continue with rest of your code, Inflate layout etc.
}
}, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_WEEK));
datePickerDialog.show();

Asp.net autocompleteextender selection issue with cursor point

I have use autocompleteextender for textbox autocomplete. I have written addition js for suggestion & value selection. Problem is after type ing some letter if I move my cursor from top to bottom then it doesn't select value where cursor is pointed. It selects value above cursor position. This problem only when cursor moves from top to bottom. Works fine when move bottom to top.
In following snapshot you can see where my cursor position & it highlighting value above.
<asp:TextBox ID="clientCode" runat="server" CssClass="field-pitch" ClientIDMode="Static"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="SearchClientCode"
ServicePath="~/auto.aspx" MinimumPrefixLength="1" CompletionInterval="100"
EnableCaching="false" CompletionSetCount="10" TargetControlID="clientCode"
ID="clientCodeExtender" runat="server" FirstRowSelected="false"
CompletionListCssClass="completionList" CompletionListItemCssClass="listItem"
CompletionListHighlightedItemCssClass="itemHighlighted"
OnClientPopulated="onClientPopulated" OnClientItemSelected="itemSelected"
BehaviorID="AutoCompleteEx"></asp:AutoCompleteExtender>
<script type="text/javascript">
function itemSelected(ev) {
var index = $find("AutoCompleteEx")._selectIndex;
if (index != -1) {
$find("AutoCompleteEx").get_element().value = $find("AutoCompleteEx").get_completionList().childNodes[index]._value;
}
else {
$find("AutoCompleteEx").get_element().value = '';
}
}
function onClientPopulated(sender, e) {
var List = $find("AutoCompleteEx").get_completionList();
for (i = 0; i < List.childNodes.length; i++) {
var _value = JSON.parse(List.childNodes[i]._value);
var abbr = _value[0];
var fullform = _value[1];
List.childNodes[i]._value = abbr;
List.childNodes[i].innerHTML = "<span>" + abbr + "(" + fullform + ")</span>"
}
}
</script>
code behind
[System.Web.Script.Services.ScriptMethod(), System.Web.Services.WebMethod()]
public static List<string> SearchClientCode(string prefixText, int count)
{
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings("conio").ConnectionString;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT clientID, clientName FROM clientsDetails where (clientID like #SearchText)";
cmd.Parameters.AddWithValue("#SearchText", prefixText + Convert.ToString("%"));
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
MySqlDataReader sdr = cmd.ExecuteReader;
JavaScriptSerializer serializer = new JavaScriptSerializer();
while (sdr.Read) {
object[] item = new object[] {
sdr("clientID").ToString(),
sdr("clientName").ToString()
};
customers.Add(serializer.Serialize(item));
}
conn.Close();
return customers;
}
You should use the given parameters of the OnClientItemSelected method:
function itemSelected(source, eventArgs) {
$find("AutoCompleteEx").get_element().value = eventArgs.get_value();
}

hide and show function keeps refreshing the page

I'm trying to have a hide and show button
Whenever i click on the button, it works but also refreshes the page at the same time. I'm not sure what is causing the refresh. This is on aspx:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#buttontest").click(function () {
$("#hello").toggle();
});
});</script>
<button id="buttontest">test</button>
<div id="hello">hello</div>
Not sure if its the aspx.cs is causing the refreshing:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnect = new SqlConnection(_connStr);
acct = new Account();
acct = (Account)Session["Account"];
if (!IsPostBack)
{
LoadCart();
DataBind();
string strCommandText = "SELECT * From Customer where Cust_Id = #Cust_Id";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#Cust_Id", 1);
//open connection and retrieve data by calling ExecuteReader
myConnect.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Lbl_FName.Text = dr["First_Name"].ToString();
Lbl_LName.Text = dr["Last_Name"].ToString();
Lbl_CNo.Text = dr["Contact_No"].ToString();
string addr1 = dr["Address"].ToString();
string addr2 = dr["Address2"].ToString();
address = new List<string>();
address.Add(dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
address.Add(dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
//Ddl_Address.Text = dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
//Ddl_Address.Text = dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
ddl_Addr.DataSource = address;
ddl_Addr.DataBind();
}
dr.Dispose();
dr.Close();
myConnect.Close();
//page load box retrieve
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT * From Card_Details where Card_Id = #Card_Id";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Id", 1);
////open connection and retrieve data by calling ExecuteReader
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
CNo1 = dr2["Card_Number"].ToString();
CNo2 = dr2["Card_Number2"].ToString();
Session["CardNo1"] = CNo1;
Session["CardNo2"] = CNo2;
CNo = new List<string>();
CNo.Add(CNo1);
CNo.Add(CNo2);
ddl_CNo.DataSource = CNo;
ddl_CNo.DataBind();
//display when first run
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
dr2.Dispose();
dr2.Close();
myConnect2.Close();
}
}
}
protected void ddl_CNo_SelectedIndexChanged(object sender, EventArgs e)
{
string cardNum1 = Session["CardNo1"].ToString();
string cardNum2 = Session["CardNo2"].ToString();
if (ddl_CNo.SelectedIndex == 0)
{
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT Name_On_Card, Card_Type, Expired_Date From Card_Details where Card_Number = #Card_Number";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Number", cardNum1);
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
}
dr2.Dispose();
dr2.Close();
// DataBind();
myConnect2.Close();
}
else if (ddl_CNo.SelectedIndex == 1)
{
SqlConnection myConnect3 = new SqlConnection(_connStr);
string strCommandText3 = "SELECT Name_On_Card2, Card_Type2, Expired_Date2 From Card_Details where Card_Number2 = #Card_Number2";
myConnect3.Open();
SqlCommand cmd3 = new SqlCommand(strCommandText3, myConnect3);
cmd3.Parameters.AddWithValue("#Card_Number2", cardNum2);
SqlDataReader dr3 = cmd3.ExecuteReader();
if (dr3.Read())
{
Lbl_CardName.Text = dr3["Name_On_Card2"].ToString();
Lbl_CardType.Text = dr3["Card_Type2"].ToString();
Lbl_EDate.Text = dr3["Expired_Date2"].ToString();
}
dr3.Dispose();
dr3.Close();
// DataBind();
myConnect3.Close();
}
}
protected void LoadCart()
{
gv_CartView.DataSource = ShoppingCart.Instance.Items;
gv_CartView.DataBind();
decimal total = 0.0m;
foreach (ShoppingCartItem item in ShoppingCart.Instance.Items)
{
total = total + item.TotalPrice;
}
decimal a = 2.0m;
decimal totalP = a + total;
Lbl_Subtotal.Text = total.ToString("C");
Lbl_TotalPrice.Text = totalP.ToString("C");
}
I'm still unfamiliar with all these, any help would be appreciated
EDIT: I've edited the button and javascript, it still caused a refresh
this looks like you might have button type as submit other wise this is not possible to happen
please make sure you added button as button not as submit button
Also please try to avoid
$("button").click(function () {
used specific button id
$("#btn_toggle").click(function () {
And you can also do.. in case if your button type is submit but you need to do return false.
$("#btn_toggle").click(function () {
$("#hello").toggle();
return false;
});
but make sure this will stop submit your from at server.
Replace server button with html button. i.e.
Replace
<asp:Button />
With
<input type="button" />
OR
do this:
$("button").click(function () {
$("#hello").toggle();
return false;
});
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#hello").toggle();
});
});</script>
<button>hello</button>
<div id="hello">hello</div>

While binding the gridview throwing an error in a process?

I am copying the selcted data from on grid to another on the click of a button. I am using postgre SQl for my apllication. Here is the link for the HTML. I am binding the data in as
NpgsqlDataAdapter adp;
NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["projop"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
private void BindPrimaryGrid()
{
DataTable dt = new DataTable();
adp = new NpgsqlDataAdapter("select user_id, username,screen_name from users", conn);
dt = new DataTable("users");
adp.Fill(dt);
gvAll.DataSource = dt;
gvAll.DataBind();
After the selection of the data & button click as
protected void btnSubmit_Click(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords"] != null)
dt = (DataTable)ViewState["SelectedRecords"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gvAll.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gvAll.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
dt = RemoveRow(gvAll.Rows[i], dt);
}
}
}
ViewState["SelectedRecords"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gvAll.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
for (int i = 0; i < gvAll.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvAll.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
Here while binding the data in function btnSubmit_Click via BindSecondaryGrid() showing an error on gvSelected.DataBind(); in function BindSecondaryGrid().
Error: DataBinding: 'HttpException - System.Data.DataRowView' does not contain a property with the name 'user_id'.
Edit: Add & Remove Codes
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["CustomerID"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["ContactName"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["Complete Name"] = gvRow.Cells[3].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
This is because your DataField specified in your GridView is incorrect. Let's try this.
<asp:BoundField DataField = "CustomerID" HeaderText = "Customer ID"
HtmlEncode = "false" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name"
HtmlEncode = "false" />
<asp:BoundField DataField = "CompleteName" HeaderText = "Complete Name"
HtmlEncode = "false" />
Please note that the DataField specified must match with the DataRow's name.
I am assuming your Datatable has column as highlighted with **:
dt.Rows[dt.Rows.Count - 1]["**CustomerID**"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["**ContactName**"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["**CompleteName**"] = gvRow.Cells[3].Text;
Let me know if this fixed this issue. Thanks

Categories