How to Make Textbox Visible And Invisible from Database - c#

Here i have textbox.Similarly, i have table tblpstatus which have two field id and Pstatus.Now what i am trying do is, if the Field Pstatus have text V then textbox must be visible else not. Now the problem is that even if the field Pstatus have text V textbox are not visible.Below is what i have:
Table tructure
id | Pstatus
1 | V
Html
<asp:TextBox ID="TextBox1" runat="server" placeholder="test" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button"/><br>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = c.getpstatus();
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Pstatus"].ToString() == "V")
{
Button1.Visible = true;
TextBox1.Visible = true;
}
else
{
Button1.Visible = false;
TextBox1.Visible = false;
}
}
}
Method used
public DataTable getpstatus()
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
string sql = "select * from tblpstatus";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

try this,
if (dt.Rows[0]["Pstatus"].ToString().equals("V"))

Related

Change DateFormat of dropdown inside gridview

I have a dropdown inside a asp gridview to Filter based on the selected dates. But when I make a selection on the dropdown I get an error, MySql.Data.MySqlClient.MySqlException: Incorrect date value: '9/12/2018 12:00:00 AM' for column 'dateValue' at row 1.
Below would be the client side code:
<asp:GridView ID="gdvTM" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvTM_PageIndexChanging" DataKeyNames="ID" PageSize="10" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc" >
<Columns >
<asp:TemplateField>
<HeaderTemplate>
Date:
<asp:Label ID="lbldate" Text="date" Visible="false" runat="server"></asp:Label>
<asp:DropDownList ID="ddlgvdate" DataTextFormatString="{0:yyyy-MM-dd}" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate >
<asp:Label ID="lbldate1" runat="server" Text='<%# Eval("date", "{0:yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
</Columns>
</asp:GridView>
Below would be the server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindDropDownList()
{
PopulateDropDown((cells.FindControl("ddlgvdate") as DropDownList), (cells.FindControl("lbldate") as Label).Text);
}
private void PopulateDropDown(DropDownList ddl, string columnName)
{
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please Select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData1");
cmd.CommandType = CommandType.StoredProcedure;
string date = null;
DateTime dateValue1 = Convert.ToDateTime(date);
string dateValue = dateValue1.ToString("yyyy-MM-dd");
dateValue = null;
if (ViewState["Date"] != null && ViewState["Date"].ToString() != "0")
{
dateValue = ViewState["Date"].ToString();
}
cmd.Parameters.AddWithValue("dateValue", dateValue);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Date"] != null ? (string)ViewState["Date"] : string.Empty, cell.FindControl("ddlgvdate") as DropDownList);
}
private void setDropdownselectedItem(string selectedvalue, DropDownList ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
DropDownList dropdown = (DropDownList)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlgvdate":
ViewState["Date"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below would be the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData1`
(in dateValue date)
BEGIN
SELECT *
FROM approved
WHERE
(dateValue IS NULL OR date = dateValue);
END
Please let me know how I can pass the date with the right format. Thanks in advance.
Thanks for John's suggestion I figured it out by using Nullable DateTime as shown below
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData1");
cmd.CommandType = CommandType.StoredProcedure;
DateTime? dateValue = null;
if (ViewState["Date"] != null && ViewState["Date"].ToString() != "0")
{
dateValue = DateTime.Parse(ViewState["Date"].ToString());
}
cmd.Parameters.AddWithValue("dateValue", dateValue);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Date"] != null ? (string)ViewState["Date"] : string.Empty, cell.FindControl("ddlgvdate") as DropDownList);
}

how to get column data when check box is checked using data list in asp.net

this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.

Show Table when SelectedValue of DropDownList is true C#

I want to show a table when a SelectedValue of my DropDownList ddlKlasse is true. I'm using asp.net empty web forms with a masterpage.
The idea is:
when ddlKlasse.SelectedValue = "2" table tblDubbelTwee must be shown
when ddlKlasse.SelectedValue = "5" table tblVierMet must be shown
when ddlKlasse.SelectedValue = "9" table tblAchtMet must be shown
I get the values in my dropdownlist from my database.
The code I have now is:
In my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
BindDropDownListKlasse();
BindDropDownListVereniging();
if (!Page.IsPostBack)
{
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
}
}
For binding the dropdown:
private void BindDropDownListKlasse()
{
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT DISTINCT AantalDeelnemers, Naam FROM Klasse;";
com.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
ddlKlasse.DataSource = dt;
ddlKlasse.DataValueField = "AantalDeelnemers";
ddlKlasse.DataTextField = "Naam";
ddlKlasse.DataBind();
conn.Close();
//Adding "Kies de klasse" optie in dropdownlist voor validatie
ddlKlasse.Items.Insert(0, new ListItem("Kies de klasse", "0"));
}
}
}
catch
{
}
}
For showing the tables:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedListItemDubbelTwee = ddlKlasse.Items.FindByValue("2");
if (selectedListItemDubbelTwee != null)
{
selectedListItemDubbelTwee.Selected = true;
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemVierMet = ddlKlasse.Items.FindByValue("5");
if (selectedListItemVierMet != null)
{
selectedListItemVierMet.Selected = true;
tblVierMet.Visible = true;
tblDubbelTwee.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemAchtMet = ddlKlasse.Items.FindByValue("9");
if (selectedListItemAchtMet != null)
{
selectedListItemAchtMet.Selected = true;
tblAchtMet.Visible = true;
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
};
}
My DropDownList:
<div class="form-inline">
<div class="form-group">
<asp:DropDownList ID="ddlKlasse" class="form-control" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlKlasse_SelectedIndexChanged"></asp:DropDownList>
</div>
</div>
One of my tables:
<asp:Table ID="tblDubbelTwee" runat="server" class="table">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Naam</asp:TableHeaderCell>
<asp:TableHeaderCell>Email</asp:TableHeaderCell>
<asp:TableHeaderCell>Lidmaatschapsnr</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
But when I run my project and select a field in my DropDownList it gives the error: System.Web.HttpException: Selecting multiple items in a DropDownList is not allowed.
Can you please help me to solve this problem?
Your current handler for DDL index change is doing something very different from what you have described. It basically checks if the list item exists in the ddl list (no matter selected or not) and then tries to select it. Since all of 3 items exist, you are effectively trying to select 3 items, which is not allowed.
What you might be looking for is a switch by selected value:
switch (ddlKlasse.SelectValue)
{
case "2":
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
break;
case "5": //similar here
case "9": //similar here
default:
// exception or something
}
refere this code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
}
void bindgrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("select DISTINCT Class from addmitionform1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlclass.DataSource = ds;
ddlclass.DataTextField = "Class";
ddlclass.DataValueField = "Class";
ddlclass.DataBind();
ddlclass.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
string id = (ddlclass.SelectedValue.ToString());
con.Close();
SqlDataAdapter da1 = new SqlDataAdapter("Select id,FirstName from addmitionform1 where Class= '" + id + "'", con);
//SqlDataAdapter da1 = new SqlDataAdapter("Select * from addmitionform1 ", con);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
}
First move BindDropDownListKlasse() and BindDropDownListVereniging() inside if (!IsPostBack), as HarveySpecter suggested.
And change ddlKlasse_SelectedIndexChanged() to:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
bool showDubbelTwee = false, showVierMet = false, showAchtMet = false;
switch (ddlKlasse.SelectedValue)
{
case "2":
showDubbelTwee = true;
break;
case "5":
showVierMet = true;
break;
case "9":
showAchtMet = true;
break;
}
tblAchtMet.Visible = showVierMet;
tblDubbelTwee.Visible = showDubbelTwee;
tblVierMet.Visible = showVierMet;
}
What you are doing now in ddlKlasse_SelectedIndexChanged() is check for each value if it's present in the dropdown, and if present select it and show the respective table.
Instead, you need to check which value is selected and show the respective table.

How to Bind column of a table in array and display result one by one on button click event?

I have created method to store column value of Questions from Question table into array and now I wanted to display in a label one by one on button click event.
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
con = new SqlConnection(str);
cmd = new SqlCommand("select Question from Questions", con);
con.Open();
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
list.Add(dtrow);
}
return list;
}
Try this....
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
CommandArgument="0" />//dEFINATION OF BUTTON ON ASPX PAGE
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list=BindDataToArray();
int I=( Convert.ToInt32(Button1.CommandArgument));
if (I < list.Count)
{
Label1.Text = list[I] as string; //Label in which u want to show message
Button1.CommandArgument = (I + 1).ToString();
}
else
{
Label1.Text = "eND OF LIST";
Button1.Enabled = false;
}
}
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
con = new SqlConnection(str);
cmd = new SqlCommand("select Question from Questions", con);
con.Open();
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
list.Add(dtrow["Question"].ToString());
}
return list;
}
Save the list in to the session
initialize a int with value = 0 and store this also in the session.
when the button is clicked
get the list and int from the session
update the label with the list[index] value where index is the int.
increment the int by one and resave it in the session.
It seems that you are looking for gridview control of asp.net.
Example http://www.dotnetfunda.com/articles/article1594-how-to-populate-gridview-from-code-behind.aspx
// in Aspx Page
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
CommandArgument="1" /><asp:Label
ID="Label1" runat="server" Text="Label"></asp:Label>
//in Aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list = BindDataToArray();
int I = (Convert.ToInt32(Button1.CommandArgument.Count()));
//int I = (Convert.ToInt32(Button1.CommandArgument));
if (I < list.Count)
{
Label1.Text = list[I] as string; //Label in which u want to show message
Button1.CommandArgument = (I + 1).ToString();
}
else
{
Label1.Text = "eND OF LIST";
Button1.Enabled = false;
}
}
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
//con = new SqlConnection(con);
SqlCommand cmd = new SqlCommand("SELECT SurveyName FROM tblSurveyName", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows) { list.Add(dtrow["SurveyName"].ToString()); }
return list;
}

Radio button list selected value not persistent in asp.net

I have two dynamically populated radio button lists. The first one gets populated on a button click, the other one on the change event of the first radio button list. The problem is only with the second list. The issue is that I am not able to retrieve the changed value of the second radio button list in the InsertButton_Click method(marked by **). It always returns the default index value i.e 0. I don't have anything in page_load event. I read quite a few similar questions but none seem to help. Please guide. Below is the asp and c# code for the same:
ASP:
<asp:Button id="SaveButton"
Text="Save"
runat="server" onclick="SaveButton_Click">
</asp:Button>
<asp:Button id="VisualiseButton"
Text="Visualise"
runat="server" onclick="VisualiseButton_Click">
</asp:Button>
<!--<hr />-->
<asp:RadioButtonList id="RadioButtonList2" runat="server" Visible="false"
onselectedindexchanged="RadioButtonList2_SelectedIndexChanged" ></asp:RadioButtonList>
<asp:RadioButtonList id="RadioButtonList1" runat="server" Visible="false" ></asp:RadioButtonList>
<asp:Button id="SaveToDBButton"
Text="Insert"
runat="server" Visible="false" onclick="InsertButton_Click">
C#:
protected void SaveButton_Click(object sender, EventArgs e)
{
String selQuery = "SELECT id, name FROM categories";
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
RadioButtonList2.DataSource = dt;
RadioButtonList2.DataTextField = "name";
RadioButtonList2.DataValueField = "id";
RadioButtonList2.DataBind();
RadioButtonList2.RepeatColumns = 3;
RadioButtonList2.AutoPostBack = true;
RadioButtonList2.Visible = true;
}
catch (SqlException ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}
}
protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
{
String catId = RadioButtonList2.SelectedValue;
SqlCommand cmdselect = new SqlCommand("SELECT DISTINCT categoryId, linkTablesCategories.tableName, tableDescription FROM linkTablesCategories, tableDescriptions where linkTablesCategories.tableName = tableDescriptions.tableName and categoryId ='" + catId + "'");
RadioButtonList1.Items.Clear();
try
{
con.Open();
cmdselect.Connection = con;
SqlDataReader dar = cmdselect.ExecuteReader();
if (dar.HasRows)
{
while (dar.Read())
{
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
li.Attributes.Add("title", dar["tableDescription"].ToString());
RadioButtonList1.Items.Add(li);
}
}
RadioButtonList1.Visible = true;
SaveToDBButton.Visible = true;
}
catch (SqlException ex)
{
//lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
}
protected void InsertButton_Click(object sender, EventArgs e)
{
String tableId="";
**tableId = RadioButtonList1.SelectedItem.Text;**
String path = Server.MapPath("~/");
string filepath = path + Session["filepath"].ToString();
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableId;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
it was with the line:
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
The categoryId was a constant value and thus the issue, again my bad.
Thanks

Categories