Trying to fill a website (webform) Textbox from a Dataset - asp.net

I'm having trouble getting the DataSet into a webform textbox with the name PrefixDescription. I tried to convert the row into a string, and I then tried to put the string into the textbox. However, nothing appears in the textbox. The DataSet does have data. I tried databinding and databind, but those don't work either.
private DirectoryEntry testAD = new DirectoryEntry();
private DataTable DT = new DataTable();
protected void Button2_Click(object sender, EventArgs e)
{
DirectorySearcher search = new DirectorySearcher(testAD);
SearchResultCollection myResults = search.FindAll();
search.PropertiesToLoad.Add("name");
DT.Columns.Add("name");
DT.Columns.Add();
foreach (SearchResult SR in myResults)
{
DataRow dr = DT.NewRow();
DirectoryEntry DE = SR.GetDirectoryEntry();
dr["name"] = DE.Properties["name"].Value;
DT.Rows.Add(dr);
DT.AcceptChanges();
PrefixDescription.Text = Convert.ToString(dr["name"]);
DE.Close();
}
}

Better yet, use a StringBuilder, something like this..
System.Text.StringBuilder builder = new System.Text.StringBuilder();
foreach (SearchResult SR in myResults)
{
DataRow dr = DT.NewRow();
DirectoryEntry DE = SR.GetDirectoryEntry();
dr["name"] = DE.Properties["name"].Value;
DT.Rows.Add(dr);
DT.AcceptChanges();
builder.Append(Convert.ToString(dr["name"]));
PrefixDescription.Text = Convert.ToString(dr["name"]);
DE.Close();
}
PrefixDescription.Text = builder.ToString();

Related

duplicate items in dropdownlist on an edit page

I have a page to edit user profile.On page load,the data loads on to the page for the given userid.The problem is that the dropdownlists have a duplicate item which is selected.as shown below :
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
ExtractUserData();
}
}
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
private void ExtractUserData()
{
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblAllUsers where UserId='PL00012'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
lblUserId.Text = rdr["UserId"].ToString();
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.SelectedItem.Text = rdr["Gender"].ToString();
ddlDisabled.SelectedItem.Text = rdr["Disabled"].ToString();
ddlState.SelectedItem.Text = rdr["State"].ToString();
ddlCity.SelectedItem.Text = rdr["City"].ToString();
}
}
What i am guessing is,the dropdownlist is loaded by BindGenderDropDown() and then the SelectedItem is added once again by ExtractData().So how can i just avoid the unwanted addition?
You can do the following while selecting DropdownList SelectedItem in ExtractUserData() method:
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(ddlGender.Items.FindByText(rdr["Gender"].ToString()));
Your code ddlGender.SelectedItem.Text = rdr["Gender"].ToString(); is displaying ---Select--- with rdr["Gender"].ToString(). This code doesn't change the Items but only chooses the item.
it may help you.
if (ddlGender.Items.Contains(ddlGender.Items.FindByText(rdr["Gender"].ToString())))
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
In your case, ddlGender.SelectedItem.Text = rdr["Gender"].ToString(); is changing text of selected index and so it is changing --Select-- to Your Selected Value.
and for selection of Item in Dropdown, I'd suggest to use below code.
ddlGender.SelectedValue = rdr["GenderId"].ToString();

Dynamically adding Table rows

I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session

Can't implicitly convert type void to object

protected void Page_Load(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS; database=employee; integrated security = SSPI"))
{
SqlCommand cmd = new SqlCommand("select * from emp",con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Option");
while (sdr.Read())
{
DataRow dr = dt.NewRow();
dr["ID"] = sdr["uid"];
dr["Name"] = sdr["uname"];
dr["Option"] = addrbl();
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private object addrbl()
{
Panel p1 = new Panel();
RadioButtonList rl1 = new RadioButtonList();
rl1.Items.Add(new ListItem("yes","1"));
rl1.Items.Add(new ListItem("no","0"));
return(p1.Controls.Add(rl1));
}
Seperate the void method from the return statement.
p1.Controls.Add(r11)); has no return value and therefore cannot be used as an argument in a return statement.
Change your return statement in addrbl() to this:
p1.Controls.Add(rl1);
return p1;
Also, you should be returning the actual object type and not just an object of type object:
private Panel addrbl() {..}

How to pass a Session to a DataTable?

In my asp project I need to write all Items form the list box into database table using TVP. I have listbox, stored procedure (passing TVP - Table Valued Parameters). The main problem is that passing DataTable is NULL, but the Session isn't. I'll send you my code form aspx.cs file (only one block, if you'll nedd more, let me know).
protected void ASPxButton1_Click(object sender, EventArgs e)
{
//DataTable dts = Session["SelectedOptions"] as DataTable;
DataTable _dt;
//_dt = new DataTable("Items");
_dt = Session["SelectedOptions"] as DataTable;
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
}
SqlConnection con;
string conStr = ConfigurationManager.ConnectionStrings["TestConnectionString2"].ConnectionString;
con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand sqlCmd = new SqlCommand("TestTVP", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("#testtvp", _dt);
tvpParam.SqlDbType = SqlDbType.Structured;
sqlCmd.ExecuteNonQuery();
}
con.Close();
}
EDIT
Debugging Screenshot
You are not adding the new rows to the DataTable. You need something like this:
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
_dt.Rows.Add(dr);
}
A secondary concern is where are you initialising Session["SelectedOptions"]? It appears that every time ASPxButton1 is clicked the code will try and add Id and Name columns to it, even if it already contains those two columns. It would seem more logical to do something like:
_dt = Session["SelectedOptions"] as DataTable;
if (_dt == null)
{
_dt = new DataTable("Items");
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
Session.Add("SelectedOptions", _dt);
}

How to bind all the rows of Dataset in gridview

can you please tell me how to bind dataset to gridview
string indno = dsRasisePo.Tables[0].Rows[0]["indno"].ToString();
for (int i = 0; i < arry.Count; i++)
{
string prodid = arry[i].ToString();
string tid = RaisePurOrder.GetTid(indno, prodid);
Dataset dsQuotation=RaisePurOrder.Bindquotation(tid);
}
gvSelectQuotation.DataSource = dsQuotation;
gvSelectQuotation.DataBind();
indent no is common only so that i gave like that i want to loop it throug the array count and passing the functions i may get more than one row in dataset now what is the problem is only last row of dataset is bindning in gridview but remaining rows are not yet bind
Well, This will give an overview how to bind the data with dataset to grid view....
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string connectionString = “server=SYS2;” + “integrated security=SSPI;” +
“database=ERPFinAccounting”;
SqlConnection myConnection;
string str_Account_Select = “SELECT * FROM AccountsTable”;
SqlCommand myCommand;
DataSet myDataSet;
myConnection = new SqlConnection(connectionString);
myConnection.Open();
myCommand = new SqlCommand(str_Account_Select, myConnection);
SqlDataAdapter mySQLDataAdapter;
myDataSet = new DataSet();
mySQLDataAdapter = new SqlDataAdapter(myCommand);
mySQLDataAdapter.Fill(myDataSet, “AccountsTable”);
GridView1.DataSource = myDataSet;
GridView1.DataBind();
}
}
i hope it will helps you

Resources