ASP.Net'e dair bir kaç ipucu

30 Tem 2005 In: .net, ipucu

Data GridView veya DataList içeridinde CheckBox kullanıyorsanız ve DB deki alan veri türü olarak integer kullanıyorsanız, checkbox u seçili checked a alabilmek için

<asp:CheckBox ID="CheckBox6" runat="server" Checked='<%# Eval("Evrak6").ToString().Equals("1") %>' />

 Data GridView da controlu özelleştirme // Format_String

<asp:TemplateField HeaderText="Sipariş No">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SIPA_ID", "{0:00000}")  %>'></asp:Label>
</ItemTemplate>                                          
</asp:TemplateField>

 ----------------------------------

 <% Response.Write((Request["yiyd"] == "1" ? "Yurtdışı" : "Yurtiçi")); %>

---------------------------------- 

 <td><%#Eval("Iptal").ToString()=="0" ?"Aktif":"Pasif" %></td> 
 <a href='<%#Eval("BAY_ID", "bayiler.aspx?op=ed&bay={0}") %>' 

----------------------------------

 DataKeyNames="ID, Name"

dtg_personel.SelectedDataKey[0].ToString()

 

--------------

     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {        

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes["onmouseover"] =  "javascript:setMouseOverColor(this);";

            e.Row.Attributes["onmouseout"] =  "javascript:setMouseOutColor(this);";

            e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink  (this.GridView1, "Select$" + e.Row.RowIndex);
        }
    }

 

var oldgridSelectedColor;

function setMouseOverColor(element)

{

    oldgridSelectedColor = element.style.backgroundColor;

    element.style.backgroundColor='yellow';

    element.style.cursor='hand';

    element.style.textDecoration='underline';

}

 

function setMouseOutColor(element)

{

    element.style.backgroundColor=oldgridSelectedColor;

    element.style.textDecoration='none';

}

 

 

 string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text; 

 DataBinder.Eval(e.Row.DataItem, "ColumnName"); 

----------------------------

 

 <asp:HyperLink ID="hlnk_git" runat="server"  NavigateUrl='<%# Eval("urunID", "urun_goster.aspx?id={0}") %>' >Ürüne Gözat</asp:HyperLink>

 

 ---------------- 

 

DataRowView drv = (DataRowView)e.Item.DataItem ;

b.CommandArgument = drv.Row["Baslik"].ToString(); 

 

 

-----------------------------------

 

  protected void dtg_ogren_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)

    {

        if (e.CommandName.ToLower() == "delete")

        {

            GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);

            LogLa(Session["inside"].ToString(), "Silindi", row.Cells[6].Text, dtg_ogrenciler.SelectedDataKey[0].ToString());

        } 

}

 

 UpdateCommand="UPDATE [Cihazlari] SET [UDate] = getdate(), [UUsern]=@UUsern,.."

 

<UpdateParameters>           

                <asp:SessionParameter Name="UUsern" Type="String" SessionField="inside" /> 

 

 

 

---------------------------------------

 

    public string SQLCalistir_Scalar(string cmd)
    {
string s="";
        SqlConnection conn_l = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr_xxx"].ConnectionString);
        SqlCommand comm_l = new SqlCommand(cmd, conn_l);

        try
        {
            if (conn_l.State != ConnectionState.Open)
                conn_l.Open();
            comm_l.CommandText = cmd;

            s=comm_l.ExecuteScalar().ToString();
            return s;
        }
        catch (Exception)
        {
            return s;
        }
        finally
        {
            if (conn_l.State != ConnectionState.Closed)
                conn_l.Close();

            comm_l.Dispose();
            conn_l.Dispose();
        }
    } 

 

public string SQLCalistir_Query(string cmd)
    {
string s="";
        SqlConnection conn_l = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr_xxx"].ConnectionString);
        SqlCommand comm_l = new SqlCommand(cmd, conn_l);

        try
        {
            if (conn_l.State != ConnectionState.Open)
                conn_l.Open();
            comm_l.CommandText = cmd;

            s=comm_l.ExecuteNonQuery().ToString();
            return s;
        }
        catch (Exception)
        {
            return s;
        }
        finally
        {
            if (conn_l.State != ConnectionState.Closed)
                conn_l.Close();

            comm_l.Dispose();
            conn_l.Dispose();
        }

    }  

 

      public DataTable SQLCalistir(string cmd)
    {
        DataTable  dt = new DataTable();
        SqlConnection conn_l = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
        SqlDataAdapter adap_l = new SqlDataAdapter(cmd, conn_l);

        try
        {
            if (conn_l.State != ConnectionState.Open)
                conn_l.Open();
            adap_l.SelectCommand.CommandText = cmd;

            adap_l.Fill(dt);
            return dt;
       }
        catch (Exception)
        {
            return dt;
        }
        finally
        {
           if (conn_l.State != ConnectionState.Closed)
                conn_l.Close();
            adap_l.Dispose();
            conn_l.Dispose();
        }
   } 

 

  ------------------------------------------------------------------------------------

 

  

GridView Control

protected void gvUsersBF_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            DataRowView drv = e.Row.DataItem as DataRowView;

                if (drv != null)

                {

            string id = drv.Row[0].ToString();

 }

        }

    }

 

DataList Control

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)

    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

        {

            DataRowView drv = e.Item.DataItem as DataRowView;

                if (drv != null)

                {

            string id = drv.Row[0].ToString();

}

        }

    }

 

Repeater Control

protected void rpErrorResolution_ItemDataBound(object sender, RepeaterItemEventArgs e)

    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

        {              

                Resolutions res = e.Item.DataItem as Resolutions;

                if (res != null)

                {

                    authorid = res.UserID.ToString();

                }

                

        }

    }

 

  ----------------- SQL sıra numarası verme -----------------------

 

 SELECT ROW_NUMBER() OVER(ORDER BY rh.RUH_ID) AS 'SNO', 

 

--------------- SQL sayfalı sıra numarası verme ----------------------

 

 WITH sayfali AS

(

    SELECT ROW_NUMBER() OVER(ORDER BY RUH_ID) AS 'SiraNO',* FROM Ruhsatlar

)

 

SELECT * FROM sayfali WHERE SiraNO BETWEEN 5 AND 10

 

 

---------------------------------

 

<a href='<%# String.Format("rdetail.aspx?r={0}&p={1}", Eval("REP_ID"),Eval("P_KODU")) %>'>Detay...</a> 

 <asp:Label ID="Label2" runat="server" Text='<%# Bind("Message") %>'></asp:Label>

 

 

--------------------------------

XML dosyası tek kayıt deger okuma

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("C:\\OBS\\CMP\\web.config");
txtServer.Text = xmlDocument.SelectSingleNode("configuration/appSettings/add[@key='Smtp']").Attributes["value"].Value;

------------------------------------

//DB Operations


---------------------------------------------------------------------------

 

ClientScript.RegisterStartupScript(GetType(), "YeniPencere", @"<script language='javascript'>alert(' Yeni sipariş kaydedildi. ');window.location.href = 'inside.aspx';</script>");

Datalist rownumber : <%#Container.ItemIndex+1 %>

JS yanlızca sayı girile bilmesi :  onkeypress="validate(event);" 

    function validate(evt) {

        var theEvent = evt || window.event;

        var key = theEvent.keyCode || theEvent.which;

        key = String.fromCharCode(key);

        var regex = /[0-9]|\,/;

        if (!regex.test(key)) {

            theEvent.returnValue = false;

            if (theEvent.preventDefault) theEvent.preventDefault();

        }

    } 

JS ile textboxun içindekini focus olunca tutma, değişmemisse çıkınca geri atama 

    var eski = ""; 

    function tut(element) {

        eski = element.value;

        element.value = '';

    }

 

   function ver(element) {

        if ('' == element.value) {
            element.value = eski;
            element.style.background = '#FFFFFF';

        }

        else
            element.style.background = '#A9F5BC';
    }

 

 İsk. 1:<asp:TextBox ID="txt_st_i1" runat="server" Width="40px" onfocus="tut(this);" onblur="ver(this);" onkeypress="validate(event);" >0</asp:TextBox>

 

 

-------------------------------------------------------

SQL Switch Case yapısı

CASE
WHEN TBLSIPATRA.CEVRIM <= 0 THEN CONVERT(decimal(18,2),TBLSIPATRA.STHAR_GCMIK)
WHEN TBLSIPATRA.CEVRIM > 0 THEN CONVERT(decimal(18,2),TBLSIPATRA.STHAR_GCMIK*TBLSIPATRA.CEVRIM)
ELSE '-'
END AS Miktar,

CASE
WHEN TBLSIPATRA.OLCUBR = '1' THEN TBLSTSABIT.OLCU_BR1
WHEN TBLSIPATRA.OLCUBR = '2' THEN TBLSTSABIT.OLCU_BR2
WHEN TBLSIPATRA.OLCUBR = '3' THEN TBLSTSABIT.OLCU_BR3
ELSE '-'
END AS Olcu 

 

 

-------------------------------------------------------------------------------------------------- 

   protected void rpt_kayitlar_ItemDataBound(object sender, RepeaterItemEventArgs e)

        {

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

            {

             = DataBinder.Eval(e.Item.DataItem, "OpTAS_ID").ToString() 

  

---------------------------------

 

public string TakipNoUret()

    {

        Random rn = new Random();

        int lenght = 5;

        StringBuilder rs = new StringBuilder();

        string charPool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        string numPool = "1234567890";

        while (lenght > 0)

        {

            if(lenght==5||lenght==4||lenght==2||lenght==1)

                rs.Append(numPool[(int)(rn.NextDouble() * numPool.Length)]);

            if (lenght == 3 )

                rs.Append(charPool[(int)(rn.NextDouble() * charPool.Length)]);

            lenght--;

        }

        if (SQLCalistirScalar("SELECT COUNT (DOS_ID) FROM DavaDosyalari WHERE TakipNo='" + rs.ToString() + "'") != "0")

            return TakipNoUret();

        return rs.ToString();

    } 

 

---------------------------------------------------------

 n.CDate = DateTime.ParseExact(txt_CDate.Text, "dd.MM.yyyy", System.Globalization.CultureInfo.CurrentCulture); 

 

 

-------------------------------------------------------

 

        //------------DB Operations------------

//------------DB Operations------------
public DataTable SQLCalistir_D(string cumle)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
{
using (SqlDataAdapter adap = new SqlDataAdapter(cumle, conn))
{
try
{
conn.Open();
adap.Fill(dt);
}
catch (Exception)
{
}
}
}
return dt;
}
public DataTable SQLCalistir_D(string cumle, SqlParameterCollection coll)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
{
using (SqlDataAdapter adap = new SqlDataAdapter(cumle, conn))
{
try
{
conn.Open();
foreach (SqlParameter p in coll)
{
SqlParameter pp = new SqlParameter(p.ParameterName, p.SqlDbType);
p.IsNullable = true;
pp.Value = (p.Value == null ? DBNull.Value : p.Value);
adap.SelectCommand.Parameters.Add(pp);
}
adap.Fill(dt);
}
catch (Exception)
{
}
}
}
return dt;
}
public string SQLCalistir_S(string cumle)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
{
using (SqlCommand comm = new SqlCommand(cumle, conn))
{
try
{
conn.Open();
return comm.ExecuteScalar().ToString();
}
catch (Exception)
{
return "";
}
}
}
}
public string SQLCalistir_S(string cumle, SqlParameterCollection coll)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
{
using (SqlCommand comm = new SqlCommand(cumle, conn))
{
try
{
conn.Open();
foreach (SqlParameter p in coll)
{
SqlParameter pp = new SqlParameter(p.ParameterName, p.SqlDbType);
p.IsNullable = true;
pp.Value = (p.Value == null ? DBNull.Value : p.Value);
comm.Parameters.Add(pp);
}
return comm.ExecuteScalar().ToString();
}
catch (Exception)
{
return "";
}
}
}
}
public string SQLCalistir_N(string cumle)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
{
using (SqlCommand comm = new SqlCommand(cumle, conn))
{
try
{
conn.Open();
return comm.ExecuteNonQuery().ToString();
}
catch (Exception)
{
return "";
}
}
}
}
public string SQLCalistir_N(string cumle, SqlParameterCollection coll)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
{
using (SqlCommand comm = new SqlCommand(cumle, conn))
{
try
{
conn.Open();
foreach (SqlParameter p in coll)
{
SqlParameter pp = new SqlParameter(p.ParameterName, p.SqlDbType);
p.IsNullable = true;
pp.Value = (p.Value == null ? DBNull.Value : p.Value);
comm.Parameters.Add(pp);
}
return comm.ExecuteNonQuery().ToString();
}
catch (Exception)
{
return "";
}
}
}
}

 

 

 

-------  New line in the title of html tags or JS alert message -------

 

&#013; 

&#10; 

  newline in JS

 

--------- FindControl in MasterPage and ContentPlaceHolder

(DropDownList)Master.FindControl("ContentPlaceHolder1").FindControl("ddl_saatsecimi" + k + "_" + j); 

 

-------- Repeater ItemCommand

  <asp:Button ID="btn_sec" runat="server" CssClass="btn btn-warning" Text=" SEÇ " CommandName="sec" CommandArgument='<%#Eval("SOZ_ID") %>' Tutar='<%#Eval("Tutar") %>'  /></td>

        protected void rpt_kayitlar_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if(e.CommandName=="sec")
            {
                //chk_tahsiledildi.ToolTip = e.CommandArgument.ToString();
                chk_tahsiledildi.Attributes["tutar"] = ((Button)e.CommandSource).Attributes["tutar"].ToString();
                chk_tahsiledildi.Attributes["sozid"] = e.CommandArgument.ToString();
                tahlarigetir(e.CommandArgument.ToString());
            }
        }

 

 

------sql execute non query with sql parameters

 

       public string scn(string cumle, string ConnStr, string p1, string p2, string p3)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString))
            {
                using (SqlCommand comm = new SqlCommand(cumle, conn))
                {
                    try
                    {
                        conn.Open();
                        SqlParameter p;
                        if (String.IsNullOrEmpty(p1))
                        {
                            p = new SqlParameter("P1", p1);
                            comm.Parameters.Add(p);
                        }

                        if (String.IsNullOrEmpty(p2))
                        {
                            p = new SqlParameter("P2", p2);
                            comm.Parameters.Add(p);
                        }

                        if (String.IsNullOrEmpty(p3))
                        {
                            p = new SqlParameter("P3", p3);
                            comm.Parameters.Add(p);
                        }

                        return comm.ExecuteNonQuery().ToString();
                    }
                    catch (Exception)
                    {
                        return "-";
                    }
                }
            }
        } 

 

 

Congratulations, you've installed DasBlog!

20 Tem 2005 In: dasBlog

Be sure to visit all the options under "Configuration" in the Admin Menu Bar above. There are 16 themes to choose from, and you can also create your own.

 

Ben Kimim ?

Celiker BahceciMerhabalar, ben Çeliker BAHÇECİ. 2004 den beri özel sektörde bilgisayar mühendisligi ve egitmenlik yapıyorum. Yine aynı yılın Ekim ayından beri sitemde .Net ile programlama ve hayat görüşüm ile ilgili makalelerimi yayınlıyorum. Blogum dışında Yazgelistir.com, mobilnedir.com gibi ineta kapsamındaki bir çok siteye Microsoft teknolojileri ile ilgili yazılar yazmaktayım.
Bu site ile sizinde hayatınızı anlamlandırmanızda bir parça katkımın olması dilegiyle...